What is Nullish Coalescing Operator?
Nullish coalescing operator is denoted by “??”(two question marks). It is also known as logical nullish assignment. This operator returns the right-hand value if the left-hand value is null or undefined. If not null or undefined then it will return left-hand value. It is introduced in ES2020. It accept the two values.
For example a and b are the two values. And we apply the ?? operator with them, then
a ?? b
If a is defined then it returns a
If a is not defined then it returns b
It means if the first value is not null or undefined then it returns the first value else it returns the second value.
In long format we can write the same code as below
var result=
(
a!==
null
&&
a!==
undefined
)
?
a:
b;
Nullish Coalescing is not a very new thing , it just a precise and good format to write the syntax.
Examples
var a; console.log(a ?? 'a is not defined'); Output: a is not defined
In the above example a is not defined hence the second value is given as an output. Now let see if a will be having some value.
var = 10; console.log(a ?? 'a is not defined'); Output: 10
Here a is having value 10. Hence the first value is returned as an output.
Another case is if the value of a is null then also the output will be the second value.
var a = null; console.log(a ?? 'a is not defined'); Output: a is not defined
How Nullish Coalescing works with the multiple arguments
var a; var b; var c = 20; var d; console.log(a ?? b ?? c ?? d); Output: 20
Here it will check step by step. Firstly it will check a is defined or not. Its not then it check the b is defined or not. Its also then it checks for the c and c is defined with value 20 so it returns 20 as an output.
Conclusion
- The nullish coalescing operator
??
provides a short way to choose the first “defined” value from a list.It’s used to assign default values to variables: - The operator
??
has a very low precedence, only a bit higher than?
and=
, so consider adding parentheses when using it in an expression.
Visit More