This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: pWBTPuRRqHMsw-txeFxsaS-4Ucv2Wytyr8KS8GLVirk
Cover

Nullish Coalescing Operator (??)

Written by @mac | Published on 2022/1/23

TL;DR
Nullish coalescing operator (??) instead of a logical or (?) is a safer operator. The OR operator will check for `falsy`. The **nullish coalesce** operator on the other hand tests for `null` and ‘undefined` only. The main purpose is to simplify assigning default values. We don’t want Javascript to do with it anything else, just return the data.

If you use @typescript-eslint you might see this error:

Prefer using nullish coalescing operator (??) instead of a logical or (||), as it is a safer operator.

Why??????

Nullish coalescing operator

Nullish coalescing is an improvement added to Typescript a while ago and officially added to 2020 Javascript. The main purpose is to simplify assigning default values.

Let’s jump to the code:

// Nullish coalescing

console.log(0 ?? 'error') // 0

console.log('' ?? 'error') // ''

console.log(null ?? 'error') // 'error'

Nothing special? Have a look at how ‘OR’ would behave

// 'good-old' OR operator

console.log(0 || 'error') // 'error'

console.log('' || 'error') // 'error'

console.log(null || 'error') // 'error'

See the difference? The OR operator will check for falsy and for Javascript 0 and ’’ are considered false in a boolean context.

See what evaluates to false here.

The nullish coalescing operator on the other hand tests for null and undefined only.

Returning an ’’ or 0 might be what we want. We don’t want Javascript to do with it anything else, just return the data!

[story continues]


Written by
@mac
During the day a developer. A husband and dad at night.

Topics and
tags
null-checks-in-code|nullish-coalescing|javascript|typescript|nullish-coalescing-operator|operators|programming|javascript-tutorial
This story on HackerNoon has a decentralized backup on Sia.
Transaction ID: pWBTPuRRqHMsw-txeFxsaS-4Ucv2Wytyr8KS8GLVirk