DEV Community

Syueying
Syueying

Posted on

Difference between `||` and `??` in JS

Basically, both operators. The most fundamental difference lies in how they interpret the result of their left expression.

|| treats its left as a boolean. Regardless of what the left expression is, it ultimately evaluates to either true or false. This is why, when the left operand is 0, '', NaN, false, etc., the final result defaults to the right operand.

On the other hand, ?? treats its left expression as a specific value, which can be null or undefined. This approach allows for more predictable results. As also mentioned in reference [1], 0, '', or NaN can also be valid values.

If you are looking for some examples, please refer to the link provided below :)

Reference

[1]Nullish coalescing operator (??)

Top comments (1)

Collapse
 
dkrathod profile image
DEVarsh Rathod

Clear and to the point explanation! Keep it up.