How To Use the Null Coalescing Operator in JavaScript

ECMAScript 2020 has a new operator for managing undefined and null values: ??

How To Use the Null Coalescing Operator in JavaScript
Photo by pine watt on Unsplash

The ECMAScript 2020 specification has a new operator for managing undefined or null values. The null coalescing operator will take an initial variable/expression/statement and attempt to use it.

In the event that it is either undefined or null, the second operand, appearing after the ??, will be used as a fallback.


Examples at Work

Below is a rundown of basic data types and how they evaluate using the ?? operator.let a;
let b = null;
let c = "";
let d = 0;
let e = false;const t1 = a ?? "Default";  // "Default"
const t2 = b ?? "Default";  // "Default"
const t3 = c ?? "Default";  // ""
const t4 = d ?? "Default";  // 0
const t5 = e ?? "Default";  // false


Null Coalescing Operator vs. Logical “or” Operator

The logical “or” short circuit operator ||, which behaves the same as the Elvis Operator, is used to reconcile two values similar to the null coalescing operator. The difference is in the rules to determine if the first operand is used.

The logical “or” will coerce the first operand as a boolean and only use it when evaluating true. This would exclude the number zero as well as empty strings, objects, and arrays.

The null coalescing operator specifically looks for an undefined or null value in the first operand as the requirement for deferring to the second.let a = 0;
let b = 7;// Logical Or Behavior
console.log(a || b);  // 7// Null Coalescing Behavior
console.log(a ?? b);  // 0

We can write them out as analogous ternary operator statements to more clearly see the difference.let a = 0;
let b = 7;let logical_or = (a) ? a : b;
console.log(logical_or); // 7let nc = (typeof a == "undefined" || a == null) ? b : a;
console.log(nc);    // 0

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe