Sitemap

When to use ?? and ||

2 min readSep 22, 2024

--

Press enter or click to view image in full size

Hello folks !

Get Damien’s stories in your inbox

Join Medium for free to get updates from this writer.

Today I would like to talk to you about operators ?? and ||.
There is a nuance that can cause a lot of knots in your brain (it’s the experience that speaks).
Let’s start with the presentations!

Nullish coalescing operator (??)

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

// Exemple:
Console.log(‘hello there’ ?? ‘General kenobi’)
// output: hello there
Console.log(null ?? ’its a trap’)
// output: its a trap
Console.log(Undefined ?? ‘General kenobi’)
// output: ‘General kenobi’

Logical OR (||)

The logical OR (||) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

// Exemple:
Console.log(‘hello there’ || ‘General kenobi’)
// output: hello there
console.log(null || ’its a trap’)
// output: its a trap
Console.log(undefined || ‘General kenobi’)
// output: ‘General kenobi’

At first glance, the behavior seems the same. But make no mistake, there is definitely a difference!
It is found in the interpretation of falsy values!
While ?? consider only null and undefined as false, || also considers 0, ‘’ as false. You can find the full list of values ​​considered falsy here.

// Here are some examples:

Console.log(false ?? 'Darth Vader')
// output: false
Console.log(false || 'Darth Vader')
// output: Darth Vader

Console.log(0 ?? 'Darth Vader')
// output: 0
Console.log(0 || 'Darth Vader')
// output: Darth Vader

Console.log('' ?? 'Darth Vader')
// output: ''
Console.log('' || 'Darth Vader')
// output: Darth Vader

Console.log(NaN ?? 'Darth Vader')
// output: NaN
Console.log(NaN || 'Darth Vader')
// output: Darth Vader

In conclusion, if you want to assign a default value in case you have null or undefined, use ??.
Regarding ||, remember that it is first the logical operator OR. If you want to use it in order to assign a value, remember that certain values ​​like 0 or ‘’ are considered false by this operator and can conduct to unexpected behaviour.

Thank you for your attention, see you soon!

--

--

Damien
Damien

Written by Damien

Fullstack developer in love with Star Wars