Nullish Coalescing Operator (??)

Written by mac | Published 2022/01/23
Tech Story Tags: null-checks-in-code | nullish-coalescing | javascript | typescript | nullish-coalescing-operator | operators | programming | javascript-tutorial

TLDRNullish 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.via the TL;DR App

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!


Written by mac | During the day a developer. A husband and dad at night.
Published by HackerNoon on 2022/01/23