Before looking into the new Nullish coalescing operator, lets first look into the Ternary (?) operator in assignment statements.
In the above code, we can see that, since the value of the variable a is not false, “how to JS” is assigned into the variable b.
Suppose we want to assign the value of a into b, irrespective of its value.
Here is where the “Nullish coalescing operator” can become more useful since it checks only for undefined or null. Below is the code with the new ?? operator
Though we can achieve all the above results using only ternary operator by adding few extra conditions or even using plain ‘if’ conditional statement, ‘??’ operator can become quite handy and make the code look more precise.
The OR operator (||) also works similar to that of ternary operator (it checks for the truthy value of the left hand side operand), where as ?? operator checks whether a variable of defined or is null.
Leave A Comment