1. ??
operator
In Javascript, ??
is known as a ‘nullish coalescing’ operator. This operator will return the first value if it is not null or undefined, otherwise it will return the second value.
1 2 3 | null ?? 5 // => 5 3 ?? 5 // => 3 |
When assigning default values to a variable, JavaScript developers often rely on the OR operator, like so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var prevMoney = 1 var currMoney = 0 var noAccount = null var futureMoney = -1 function moneyAmount(money) { return money || `You currently do not own an account in the bank` } console.log(moneyAmount(prevMoney)) // => 1 console.log(moneyAmount(currMoney)) // => `You currently do not own an account in the bank` console.log(moneyAmount(noAccount)) // => `You currently do not own an account in the bank` console.log(moneyAmount(futureMoney))// => -1 |
Above we have created a moneyAmount
function moneyAmount
in charge of returning the user’s current balance. We used the ||
operator to identify users without an account. However, what does that mean when the user doesn’t have an account? It would be more accurate to consider no account as null instead of 0 because bank accounts can exist without money (or negative money). In the above example, the ||
operator see 0 as a falsy value so don’t register that our user has an account with 0 $. We fix it with the operator ??
1 2 3 4 5 6 7 8 9 | var currMoney = 0 var noAccount = null function moneyAmount(money) { return money ?? `You currently do not own an account in the bank` } moneyAmount(currMoney) // => 0 moneyAmount(noAccount) // => `You currently do not own an account in the bank` |
Operator ??
allows us to assign default values while removing falsy and empty strings.
2. ??=
operator
The ??=
operator is also known as the ‘logical nullish assignment’ operator and is closely related to what we learned earlier.
1 2 3 4 5 6 | var x = null var y = 5 console.log(x ??= y) // => 5 console.log(x = (x ?? y)) // => 5 |
The assignment operator will only assign a new value if the current value is null / undefined. The example above highlights how this operator demonstrates the assignment syntax for nullish.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function gameSettingsWithNullish(options) { options.gameSpeed ??= 1 options.gameDiff ??= 'easy' return options } function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') { return {gameSpeed, gameDiff} } gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => { gameSpeed: 1, gameDiff: 'easy' } gameSettingsWithDefaultParams(null, null) // => { gameSpeed: null, gameDiff: null } |
One notable difference here is the way in which the above functions treat null values. Default parameters override default values with null arguments, and ??=
operator does not. Both the default parameter and the Specify nullish will not overwrite the value for undefined
3 ?.
operator
Operator ‘Optional chaining’ ?.
Allows developers to read property values nested within a sequence of objects without having to explicitly validate each property along the way to the desired property. When a reference is nullish, the expression stops and returns an undefined value.
1 2 3 4 5 6 7 8 9 10 11 12 | var travelPlans = { destination: 'DC', monday: { location: 'National Mall', budget: 200 } }; const tuesdayPlans = travelPlans.tuesday?.location; console.log(tuesdayPlans) // => undefined |
Now, let’s incorporate everything we’ve learned so far and add Tuesday to our new travel plan!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function addPlansWhenUndefined(plans, location, budget) { if (plans.tuesday?.location == undefined) { var newPlans = { plans, tuesday: { location: location ?? "Park", budget: budget ?? 200 }, }; } else { newPlans ??= plans; //will only override if newPlans is undefined console.log("Plans have already been added!"); } return newPlans; } var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theatre", null); console.log(newPlans) // => { plans: //{ destination: 'DC', // monday: { location: 'National Mall', budget: 200 } }, // tuesday: { location: 'Ford Theatre', budget: 200 } } newPlans = addPlansWhenUndefined(newPlans, null, null) // logs => Plans have already been added! // returns => newPlans object |
We have now created a function that adds plans for an object that currently does not have the nested property of tuesday.location. We have also used nullish operators to provide default values. This function will accept false values like ‘0’ as a valid parameter. Which means our budget can be set to 0 without any errors.
4. ?
operator
Operator ?
has 3 operands: a condition, an expression that will do if the condition is true, and an expression that will do when the condition is false.
1 2 3 4 5 6 7 | function checkCharge(charge) { return (charge > 0) ? 'Ready for use' : 'Needs to charge' } console.log(checkCharge(20)) // => 'Ready for use' console.log(checkCharge(0)) // => 'Needs to charge' |
Operator
?
can also be used in assigning values to variables1 2 3 4 | var budget = 0 var transportion = (budget > 0) ? 'Train' : 'Walking' console.log(transportion) // => 'Walking' |
We can also use it to reproduce the behavior of the nullish assignment.
1 2 3 4 5 6 7 | function nullishAssignment(x,y) { return (x == null || x == undefined) ? y : x } var x = nullishAssignment(null, 8) // => 8 var y = nullishAssignment(4,8) // => 4 |
Can we use operators
?
to refactor the above example1 2 3 4 5 6 7 8 9 10 11 | function addPlansWhenUndefined(plans, location, budget) { var newPlans = plans.tuesday?.location == undefined ? { plans, tuesday: { location: location ?? "Park", budget: budget ?? 200 }, } : console.log("Plans have already been added!"); newPlans ??= plans; return |