The JS Bifrost — Nullish Coalescing (??) Operator
what-why-how of nullish coalescing operator along-with chaining and logical operations
Welcome back to “The JS Bifrost”, your pathway to rock solid foundation for a God-level JavaScript. This is the second article in the series. Our focal point for this one is — the new nullish coalescing operator.
WHAT?
It is a new Logical operator meant for short-circuiting to handle default values.
It returns it’s right-hand side operand when its left-hand side operand is null
or undefined
, otherwise returns its left-hand side operand.
WHY?
To assign some default values to the variable if it is null or undefined we use nullish coalescing.
On the other hand, if we use logical OR(||) operator it will return left-hand side operand only if it is a falsy value, which is not null
or undefined
.
Left-Hand-side ?? Right-Hand-side
or
result = x ?? y
It’s equivalent is:
result = (x !== null && x!== undefined) ? x: y;
HOW?
Let’s deep dive and see how nullish coalescing works on primitive data types in javascript with few examples.
String:
In above example, we are comparing null value and empty string with string. Result will be Bob and empty string respectively. Because (??) will only short-circuit the null value not an empty string.
Integer:
In above example, we are comparing 0 and 20, output is 0 because left-hand side operand is not null
or undefined
.
Boolean:
In above example, we are comparing Boolean value with null
and undefined
and the result we are getting is boolean because they are not null
or undefined
.
WHAT IS Nullish Coalescing Operator Chaining?
In the above example, we are using multiple(chain of) nullish coalescing(??) operator and checking the values of each operand from left to right till the time it will not find a value which is not null
or undefined
in our case, it is 5 as output.
Chaining with OR and AND operator
In above example, we are combining multiple logical ( && and || ) operator with nullish coalescing. we are getting the syntax error. so to resolve the above error we need to separate the operands with parenthesis(refer below example) to explicitly indicates the precedence.
Browser Compatibility
Most of the modern browsers support nullish coalescing operator(??), but with few exceptions from a compatibility perspective. Below is a quick summary.
Conclusion
There are a whole lot of bugs that we can face while doing programming we can simply avoid those by using nullish coalescing operator.
There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.
— C.A.R. Hoare, 1980 ACM Turing Award Lecture
I hope this article is useful, when and how to use nullish coalescing operator (“??”). Thanks for reading!
Stay tuned for more under our ‘The JS Bifrost’ !!