Journey of Nullish coalescing operator (?? 😮)
Nullish coalescing operator…wait!! even i am not able to pronounce it 😶, but who cares 😋.
Let’s start the journey !!!!!!😎
The nullish coalescing operator
?? provides a short syntax for selecting a first “defined” variable from the list.
The result of
a ?? b is:
aif it’s not
x = a ?? b is a short equivalent to:
x = (a !== null && a !== undefined) ? a : b;
Yeahhh!!!!! we decoded the mystery 😎….
But why to use this, we already have different methods for this.🤐
So, this came into picture when we have some issues (not exactly the issues.. i guess🙄 ) with OR (||) operator.
Comparison with OR (||)
|| operator can be used in the same way as
??. Actually, we can replace
|| in the code above and get the same result.
The important difference is that:
||returns the first truthy value.
??returns the first defined value.
This matters a lot when we’d like to treat
null/undefined differently from
Lot of theory now. Let’s look a example 😇
money = money ?? 100;
100 if it’s not defined.
Let’s compare it with
money || 100 treats zero money as unset, same as
undefined or any other falsy value. So the result is
money ?? 100 returns
100 only if
money is exactly
undefined. So the
alert shows the money value
0 “as is”.
Which behavior is better depends on a particular use case. When zero money is a valid value😥 , then
?? is preferable.
Waitt.. It will not work in IE😥.But no issues ‘Polyfills are the saviours😇’
Thank you for reading 🙌
Clap! if this was useful for you 👋