Let’s learn some new JS operators!
Have you ever spent a lot of time reading through the Mozilla docs? If so, you know that there is a lot of information about JavaScript out there. This makes it easy to ignore the regular JavaScript operators.
However, just because these operators are uncommon doesn’t mean they are not strong! Each of them looks syntactically similar, but remember to read about each as they work in different ways.
Let’s find out together!
1. Operator ??
In JavaScript, the ?? operator is called the nullish binding operator . This operator will return the first argument if it is not null / undefined , otherwise it will return the second argument. Let’s see an example.
1 2 3 |
null ?? 5 // => 5 3 ?? 5 // => 3 |
When assigning default values to a variable , JavaScript developers often rely on the logical 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 I have created a moneyAmount function that returns the current balance of the user. The || operator Used to identify users without an account. However, what does that mean when a 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). In the above example, the || operator see 0 as an error value and therefore do not register that our users have a $ 0 account. Fix this by using the nullish combination 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` |
To summarize, operator ?? allows us to specify default values while ignoring dummy values like 0 and empty strings.
2. Operator ?? =
?? = is also known as the nullish logical assignment operator and is closely related to what we have learned before. Let’s see how they come together.
1 2 3 4 5 6 |
var x = null var y = 5 console.log(x ??= y) // => 5 console.log(x = (x ?? y)) // => 5 |
This assignment operator will only assign a new value if the current value is null or unknown. The example above highlights how this operator is essentially a syntax line for assigning nullish. Next, let’s see how this operator differs from the default parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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 } |
3. Operator?.
Optional string operator?. Allows developers to read the values of properties deeply nested in a sequence of objects without having to explicitly validate each reference during execution. When a reference is empty, expression stops evaluating and returns an undefined value. Let’s see an example.
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 |
See the next example.
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 |
The example above combines all of the operators we have learned so far. Now we have created a function to add the plan. I have also used the 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. Operators?
The ternary operator? Accepts three operands: a condition, an expression to execute if the condition is true, and an expression to execute if the condition fails. See the following example:
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' |
If you’ve taken the time to learn JavaScript, you may have seen ternary operators before. However, did you know that ternary operators can be used to assign variables?
We can even use it to assign nullish values.
1 2 3 4 |
var x = 6 var x = (x !== null || x !== undefined) ? x : 3 console.log(x) // => 6 |
See the next example:
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 |
Before we finish, use the ternary operator to refactor the function from the previous example.
1 2 3 4 5 6 7 8 9 10 11 12 |
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 newPlans; } |