Reassign a Variable if Null or Undefined using JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

Reassign a Variable if Null or Undefined #

To reassign a variable if it's equal to null or undefined, use the logical nullish assignment (??=) operator, e.g. myVar ??= 'updated value'. If the value to the left-hand side of the operator is equal to null or undefined, the assignment is performed.

index.js
let myVar; myVar ??= 'updated value'; console.log(myVar); // ๐Ÿ‘‰๏ธ "updated value"

We used the logical nullish assignment (??=) operator to assign a value to the myVar variable if it's value is equal to null or undefined.

If the value of the myVar variable is not equal to null or undefined, the logical nullish assignment (??=) operator short-circuits and does not assign the value to the variable.

Notice that we used the let keyword to declare the variable, had we used const, we would not be able to reassign it.

An alternative approach is to use the nullish coalescing (??) operator.

Use the nullish coalescing operator to reassign a variable if it's equal to null or undefined, e.g. myVar = myVar ?? 'new value'. The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined, otherwise it returns the left-hand side operand.

index.js
let myVar; myVar = myVar ?? 'updated value'; console.log(myVar); // ๐Ÿ‘‰๏ธ "updated value"

If the value to the left of the nullish coalescing operator (??) is equal to null or undefined, the value to the right is returned, otherwise the value to the left of the operator is returned.

If the value stored in the myVar variable is anything other than null and undefined, it will get assigned the string updated value, otherwise it will get assigned its current value.

Alternatively, you can use a simple if statement.

index.js
let myVar; if (myVar === undefined || myVar === null) { myVar = 'updated value'; } // ๐Ÿ‘‡๏ธ "updated value" console.log(myVar);

We used the logical OR (||) operator to chain 2 conditions. If either of the conditions returns a truthy value, the if block is ran.

For our purposes we check if the myVar variable is equal to undefined or null, if it is, we reassign its value to the updated value string.

This is definitely the simplest and most widely used solution. It's quite explicit and easy to read. A basic if statement is my preferred approach when working on a team, where developers might not be familiar with some of the newer operators.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee