What Is the JavaScript Logical Nullish Assignment Operator?

Introduced in ES12, you can use the logical nullish assignment operator (??=) to assign a value to a variable if it hasn't been set already. Consider the following examples, which are all equivalent:

// using the ternary operator
let x;

x = (null !== x && typeof x !== 'undefined') ? x : (x = 'default');
// ES11+
// using the null coalescing operator
let x;

x ?? (x = 'default');
// ES12+
// using the logical nullish assignment operator
let x;

x ??= 'default';

The null coalescing assignment operator only assigns the default value if x is a nullish value (i.e. undefined or null). For example:

// ES12+
let x = null;
x ??= 'bar';

console.log(x); // 'bar'
// ES12+
let x;
x ??= 'bar';

console.log(x); // 'bar'

In the following example, x already has a value, therefore, the logical nullish assignment operator would not set a default (i.e. it won't return the value on the right side of the assignment operator):

// ES12+
let x = 'foo';
x ??= 'bar';

console.log(x); // 'foo'

In case, you use the nullish assignment operator on an undeclared variable, the following ReferenceError is thrown:

// ES12+
// ReferenceError: x is not defined
x ??= 'bar';

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.