Today I Learned

hashrocket A Hashrocket project

Nullish coalescing operator - ??

Ever need to have a back up default value when something is null or undefined in Javascript? Well a fairly recent addition to JS has got you covered. The Nullish coalescing operator ?? may help you on your logical path.

If the first half of the epresssion is 'nullish', it will return the latter.

const defaultValue = 'I WIN'
const someVariable = null
someVariable ?? defaultValue
=> 'I WIN'

compare this to using || in which the first half of expression needs to evaluate falsey to get into the latter portion.

As it is a newer part of the JS API make sure to check for browser support. There is also a polyfill available.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.