Journey of Nullish coalescing operator (?? 😮)
Hey folks!!!
Today we are going into one new topic of javascript or i can say modern javascript 🤨.
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:
a
if it’s notnull
orundefined
,b
, otherwise.
So, 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 (||)
The OR ||
operator can be used in the same way as ??
. Actually, we can replace ??
with ||
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 0😯.
Lot of theory now. Let’s look a example 😇
money = money ?? 100;
This sets money
to 100
if it’s not defined.
Let’s compare it with ||
:
Here, money || 100
treats zero money as unset, same as null
, undefined
or any other falsy value. So the result is 100
.
The money ?? 100
returns 100
only if money
is exactly null
or 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 👋