DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

Javascript: null coalescing

In javascript, null coalescing (??) operator is used to get first "defined" variable from list.

For eg: x=a ?? b

Which is same as saying,
x = (a!=null || a!=undefined)?a:b


It reduces amount of code needed to check for null or undefined value.


We cannot use ?? Operator along with && or || operator without explicit parenthesis.

Eg: x = a && b ?? c will raise syntax error.

x=(a && b) ?? c
Is correct way


We can use (||) operator as replacement to (??). But there is small difference between them.
?? returns first defined value while || returns first truth value.


Discussion (0)