[Solved-4 Solutions] “null coalescing” operator in JavaScript - JavaScript Tutorial
Problem:
Is there a “null coalescing” operator in JavaScript ?
Solution 1:
- In C# the “null coalescing” operator is ?? operator, but JavaScript has an operator like this, i.e. ||.
- The operator || is the logical OR operator. If any of the two operands are non-zero, then the condition becomes true. Here we can use the operator || with var in JavaScript:
- Here the following example is given below,
- We can see the operation went till the right-most operand since the previous ones were always coerced into false. The returned value is not true but the value it self. In this case 5.
So we can try this one,
- We know that the operation inside the if clause went till the right-most operand and since this operand was coerced into true the console will log the message.
Then 5 is implicitly coerced to true, the code enters the if clause.
Solution 2:
The JavaScript equivalent of the C# null coalescing operator (??)
is using a logical OR (||)
:
Regardless of the type of the first operand, if casting it to a Boolean results in false
, the assignment will use the second operand. Beware of all the cases below:
This means: