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 š