One of the new implementations of the last ECMAScript standard is the nullish coalescing operator. Basically, it is a new logical operator that returns its right-hand side operand when its left-hand side operand is null
or undefined
and otherwise returns its left-hand side operand.
At the time of writing, it is in Stage 4, which means that this feature is ready for inclusion in the formal ECMAScript standard.
Let's see a basic example:
const foo = null ?? "James";
console.log(foo); // > "James"
Here we can clearly see that because the left-hand side is null
, the value "James"
is assigned to the foo
variable. With that said, what is the difference with the OR (||
) operator? Don't we get the same result?
The answer is YES, but suppose you consider some falsy values as usable like an empty string or 0
. So, let's modify the previous example:
const foo = "" ?? "James";
const bar = "" || "James";
console.log(foo); // > ""
console.log(bar); // > "James"
The variable foo
is assigned with ""
because ""
is not strictly equal to null
or undefined
. On the other hand, "James"
is assigned to the variable bar
because ""
is a falsy value.
That being so, the nullish coalescing operator can prevent some unexpected behaviors in cases you consider some falsy values as valid ones.
One last thing about this new feature is that you can combine it with both &&
and ||
operators but you must provide parenthesis to explicitly indicate precedence. Otherwise, a SyntaxError will be thrown:
null || undefined ?? "foo"; // raises a SyntaxError
(null || undefined) ?? "foo"; // This is OK!
I hope this article helps you to know more about the ??
operator.
Got any questions? Leave a comment below.
Thank you for reading :)
Top comments (0)