What Is the JavaScript Logical Nullish Assignment Operator?

JavaScript logical nullish assignment operator (??=) explained

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';

Hope you found this post useful. It was published . Please show your love and support by sharing this post.