Well, you must be wondering what I am going to talk about! Today, I learn about a peculiar operator which modern javascript supports, known as Nullish Coalescing Operator(??).
So what is this operator?
Syntax:
Expression1 ?? Expression2
So, from the above syntax, you can see that
- It is a binary operator( i.e. it requires two operands / expressions ) and
- returns the value of the first expression which is not null or undefined Example:
let age = a ?? b
Here, the age variable will contain the value of a
if it is not null
or undefined
, otherwise, it will contain the value of b
.
Well, Basically It turns into the below code
// consider a and b is known
if(a == null || a == undefined)
{
age = b;
}
else
{
age = a;
}
NOTE: ?? operator works similar to the || (logical-OR) but the only difference is that the || operator checks for falsy
values and ?? checks for the values that are null
or undefined
let var1 = 0 ?? 23 // var1 = 0
let var2 = 0 || 23 // var2 = 23
Limitation:
- We can't use this ?? operator with && or || without explicit parantheses. Example:
0 && 2 ?? 3 // Uncaught SyntaxError
( 0 && 2 ) ?? 3 // 0
2nd code works perfectly fine and returns 0 because the code becomes 0 ?? 3
and because 0 is not null or undefined the output is 0. 😉
I Hope, you learnt something new today and will find this useful. As this is my first post on this amazing platform, please spare me, if the post has any error.
Have a good day and night as well 😛
Resources: (for more information)
https://javascript.info/nullish-coalescing-operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
Top comments (0)