DEV Community

Cover image for Quick tip about || vs ??

Posted on • Updated on

Quick tip about || vs ??

The nullish coalescing operator will help us to define nullary values equality (null or undefined), unlike the || operator.

const basketValue = 0;
const orBasketValue = basketValue || 14;
const nullishBasketValue = basketValue ?? 14;
Enter fullscreen mode Exit fullscreen mode

What happened here ?

The nullish coalescing operator (the ??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined. Otherwise returns its left-hand side operand.

|| implicitly converts our number to nullish value and returns 14.
?? checks the value of basketValue (different to nullary values) and returns 0

So, in our example, the orBasketValue is equal to 14 and nullishBasketValue is equal to 0.

That's it, make good use of it !

I'm not a native English speaker so, thanks in advance if you want to improve my article with correct syntax/grammar/sentences.

I can accept all kind remarks :)

Cover by JC Dela Cuesta on Unsplash

Top comments (2)

brack0 profile image
Denis SOURON • Edited

This is a really nice feature to pull apart nullish and falsy values. I'd love to have this kind of behavior in conditionnal evaluation. Sometimes zero (as number) or empty string are expected values and having to handle nullish versus falsy is not really elegant. Hope this will come soon.

necraidan profile image
Benjamin🦸‍♂️Auzanneau™ • Edited

If you want to try it, it's available in TypeScript since the version 3.7 !
In other hand, you can also try it directly in some browsers.
Let's give it a try ! ❓❓