The Nullish Coalescing Operator (??)

The Nullish Coalescing Operator (??)

ยท

1 min read

Nullish coalescing operator returns the right side operand when the left side operand is Nullish. Likewise left side, an operand is returned when the right side operand is Nullish. Often used to provide a default value if the first one is missing.

Ummm you must be thinking what is this Nullish word indicates? So Nullish is null or undefined.

Let's look at some examples to understand them better:

const nullishExample = {
    value:null
}
console.log(nullishExample.value ?? 'I am Here to Learn')
//output: I am Here to Learn
console.log('Naruto'?? undefined)
//output: Naruto

If we have logical OR then why do we need a Nullish Coalescing operator ?๐Ÿค”

In the logical OR operator, it returns the right side operand if the left-hand side operand has a falsy value.

We have falsy values: 0, ' ', false, NaN, null, undefined.
So the problem comes here when you want to evaluate 0 as a value.

Let's see an example

let value = 0 || 26
//output 26

Above example 0 is treated as the falsy value that's why it's returning the right side operand that is 26.

let's use the same example with nullish coalescing operator.

let value = 0 ?? 26
//output: 0

Isn't it amazing ๐Ÿค“.

ย