What is the nullish coalescing operator (??) in JavaScript?

The nullish coalescing operator ( ?? ) was introduced in ECMAScript 6 as a way to handle the coalescing of null and undefined values. It is a binary operator that takes two operands: the left operand is the expression to be evaluated, and the right operand is the default value to be used if the left operand is null or undefined .

The nullish coalescing operator works by first checking to see if the left operand is null or undefined . If it is, then the right operand is returned. If the left operand is not null or undefined , then the left operand is evaluated and the result is returned.

For example, the following code uses the nullish coalescing operator to determine the value of x :

var x = null;
x ?? 1; // 1

In this example, if x is null , then 1 is returned. If x is not null , then the result of x is returned.

The nullish coalescing operator can also be used to set a default value for a variable. For example, the following code sets the value of y to be 1 unless x is null or undefined , in which case y will be set to 0 :

var y = 0;
var x = null;
x ?? y; // 0

The nullish coalescing operator can also be used in arrays. For example, the following code sets the value of z to be the empty string unless x is null or undefined , in which case z will be set to []:

var z = [];
var x = null;
x ?? z; // []
💡
Need a writer? Want to work with me? I have a subscription copywriting service available at Zipply.io. Subscribe to a set number of words and split it into as many copy assets as you need. Scale your startup, small business, or MVP. Upgrade, downgrade and pause at any time. Start your subscription here.