Nullish coalescing (??) and Optional chaining (?.)

We all are familiar with the logical OR (||) operator. It returns the right-hand side operator when the left-hand side operator is a falsy value.
console.log(10 > 20 || 20);
//20
But what if you want to use falsy values like 0 , '' , false, and NaN then you can encounter unexpected results when it comes to the OR operator. And will have to write nested if-else logic to return the falsy values in your code.
Falsy values in javascript are 0 , null , '' , undefined, false, and NaN .
In order to save ourselves from this lengthy nested loops Nullish coalescing (??) is introduced.
Nullish coalescing (??)
Nullish coalescing operator (??) returns the right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand. It only checks for nullish values(null or undefined).
console.log(null ?? 20);
//20
console.log(undefined ?? 20);
//20
Comparing logical OR (||) and Nullish coalescing (??)
Nullish coalescing provides an alternate way to deal with falsy values except for null and undefined.
For falsy value
0const person = { name: "Jonas", age: 0 }; console.log(person.age || 1); // 1 console.log(person.age ?? 1); // 0For falsy value
''(empty string)console.log('' || "Hello"); // Hello console.log('' ?? "Hello"); // ''For falsy value
falseconsole.log(false || true); // true console.log(false ?? true); // falseFor falsy value
NaNconsole.log(NaN || 20); //20 console.log(NaN ?? 20); //NaNCombining both OR (
||) and Nullish coalescing(??)We cannot directly combine (
||) with (??) as the precedence of (??) is same as that of (||) and hence it will throw a syntax error.console.log(10 > 20 || 30 ?? 40); //Uncaught SyntaxError: missing ) after argument listHowever, by providing parenthesis, we can explicitly indicate precedence is correct.
console.log((10 > 20 || 30) ?? 40); //30
Optional chaining (?.)
The optional chaining operator (?.) is used to check nested object properties or call a function that could be null or undefined (nullish values), the expression short circuits and evaluates to undefined instead of throwing an error.
Usually when we try to access the properties of an object or call a function that doesn't exist it throws an error. So optional chaining provides a secure way of checking whether the property or function exists or not.
const person = {
name: "Jonas",
age: 0
};
console.log(person.country?.state);
//undefined
Normally, it would have thrown a type error but by using optional chaining we can avoid that. Another approach could be to use AND(&&) operator.
const person = {
name: "Jonas",
age: 0
};
if(person.country && person.country.state)
console.log(person.country.state);
// undefined
But as you can see it's such a hassle to type all those things and that's where optional chaining saves our lives. Some points to remember while using optional chaining :
Optional chaining on the left-hand side of an assignment
Optional chaining doesn't work on the left-hand side of an assignment. This results in an error. Since the optional chaining will return undefined.
let user = {}; user?.message = "Hello"; // Uncaught SyntaxError: Invalid left-hand side in assignmentOptional chaining with function calls
We can use optional chaining when we are trying to call a function that may not exist and automatically return undefined instead of throwing an error.
const person = { name: "Jonas", age: 0 }; person.country?.(); // undefinedCombining Optional chaining with the Nullish coalescing operator
We can use both (
??) and (?.) at the same time and set a default value if our optional chaining returns nullish values.const person = { name: "Jonas", age: 0 }; console.log(person?.occupation ?? "Not mentioned"); // Not mentioned
Conclusion
Nullish coalescing operator (??) returns the right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand.
The optional chaining operator (?.) is used to check nested object properties or call a function that could be null or undefined, the expression short circuits and evaluates to undefined instead of throwing an error.
Both nullish coalescing operator (??) and optional chaining operator(?.) checks for nullish values(null or undefined).



