Nullish Coalescing Operator (??) by@mac

Nullish Coalescing Operator (??)

Mac Wasilewski HackerNoon profile picture

Mac Wasilewski

During the day a developer. A husband and dad at night.

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.



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!


Signup or Login to Join the Discussion


Related Stories