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.