chan.dev / posts

Nullish Coalescing and when you should use it

Nullish presented as a subset of falsy

The ?? operator is identical to || when the left side is null, undefined, or truthy.

They differ when the left side is falsy but not null or undefined.
In this case: ?? returns the left side.
|| will returns the right side.

In practical terms, ?? returns values with an operable type (string, number, bigint, boolean, etc.) even when their values are falsy.

falsy contains nullish

falsy is a superset of nullish.
It’s a square, rectangle, paralellagram situation.

Examples

Number

console.log(42 || 'default') // 42
console.log(42 ?? 'default') // 42
console.log(0 || 'default') // "default"
console.log(0 ?? 'default') // 0

String

console.log('juniper' || 'default') // "juniper"
console.log('juniper' ?? 'default') // "juniper"
console.log('' || 'default') // "default"
console.log('' ?? 'default') // ""

Boolean

console.log(true || 'default') // true
console.log(true ?? 'default') // true
console.log(false || 'default') // "default"
console.log(false ?? 'default') // false

Nullish

console.log(undefined || 'default') // "default"
console.log(undefined ?? 'default') // "default"
console.log(null || 'default') // "default"
console.log(null ?? 'default') // "default"