Skip to main content

Quick tip about || vs ??

· One min read
Benjamin Auzanneau

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;

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