Null Coalescing Operator in JavaScript

Null Coalescing Operator in JavaScript | When its left-hand side operand is null or undefined, the nullish coalescing operator (??) returns its right-hand side operand; in all other cases, it returns its left-hand side operand.

The logical OR (||) operator is a special example of the nullish coalescing operator. If any false value other than null or undefined is present in the left operand, the latter returns the right-side operand. In other words, if you consider any false values (such ” or 0) to be valid, you can experience unexpected behavior if you use || to assign some default value to another variable foo. More instances are shown below.

The null coalescing operator directly above the conditional (ternary) operator and below | |, has the fifth-lowest operator precedence. See more:- JavaScript Operator Precedence. Directly combining the AND (&&) and OR (||) operators with?? is not possible. In these circumstances, a syntax error will be raised.

null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a Syntax Error

Instead, use parenthesis to distinctly denote priority:-

(null || undefined) ?? "foo"; // returns "foo"

Syntax:-
leftExpr ?? rightExpr

The operator for null coalescence ?? enables quick selection of the first “defined” value from a list.

It’s employed to give variables default values:-

// set height=130, if height is null or undefined
height = height ?? 130;

When employing the operator?? in an equation, take into account inserting parentheses because it has relatively low precedence, only slightly higher than the ? and =.

Note that It is prohibited to use it without explicit parenthesis with || or &&.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *