paint-brush
Nullish Coalescing Operator (??)by@mac
758 reads
758 reads

Nullish Coalescing Operator (??)

by Mac WasilewskiJanuary 23rd, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - Nullish Coalescing Operator (??)
Mac Wasilewski HackerNoon profile picture


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!