Replacing the Ternary Operator with the Nullish Coalescing Operator

Ole Ersoy
Dec 17, 2024

--

Image by darkness_s from Pixabay

Scenario

We are testing if n is null or undefined or some other non falsy value and want a shorter version of this.

const boo = n ? n : 'somethingelse';

Approach

Use the nullish coalescing operator.

const foo = n ?? 'somethingelse';

Given the usage context could also do (As Jon pointed out in the comments), all though using the ?? operator is more strict.

const foo = n || 'somethingelse';

One thing to note here is that we know, based on the context ( As defined in the scenario), that foo is going to always be null , undefined , or somethingelse and this is important semantically.

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

Responses (2)