Prefer video? See my Egghead lesson on Null Coalescing

The recent TypeScript 3.7 release introduced many people to some interesting Stage 3 JavaScript features (update: now at Stage 4!), including the nullish coalescing operator ??. Of course, you don’t need TypeScript to use it — you can either configure Babel to enable this feature, or just wait until it lands in the ECMA standard.

Let’s talk about why you’d want to use it, rather than the usual double pipe operator. Consider this example:

The boolean problem

const chickenPref = false;
const globalPref = true;
const serveUserChicken = chickenPref || globalPref; // evaluates to true

This user has been crystal clear that she does not like chicken — but the OR operator (||) doesn’t care. It will still continue and evaluate the globalPref, as if the chickenPref has not been defined. Why? Because the OR operator doesn’t care what exactly the value of the left operand is —it coerces the left operand into a boolean, and if it’s false, it’ll continue to evaluate the right one, resulting in one unhappy user. …


Yoni Weisbrod

Developer, community contributor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store