Set a Variable's Value if it's Null using JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

Set a Variable's Value if it's Null #

Use the logical nullish assignment operator to set a variable's value if it's equal to null, e.g. myVar ??= 'new value'. The logical nullish assignment (??=) operator assigns the provided value to the variable if it's equal to null or undefined.

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

We used the logical nullish assignment (??=) operator to assign a value to the v1 variable if it stores a null or undefined value.

If the value of the v1 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.

Set a Variable's Value if it's Null using Nullish Coalescing #

To set the value of a variable is it's equal to null, use the nullish coalescing operator, 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 v1 = null; v1 = v1 ?? 'new value'; console.log(v1); // ๐Ÿ‘‰๏ธ "new 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 v1 variable is anything other than null and undefined, it will get assigned the string new value, otherwise it will get assigned its current value.

Set a Variable's Value if it's Null using Ternary #

Use a ternary operator to set a variable's value if it's equal to null, e.g. v1 = v1 === null ? 'new value' : v1;. If the condition to the left-hand side evaluates to a truthy value, the ternary operator returns the value to the left of the colon, otherwise the value to the right is returned.

index.js
let v1 = null; v1 = v1 === null ? 'new value' : v1; console.log(v1); // ๐Ÿ‘‰๏ธ "new value"

A ternary operator is very similar to an if/else statement.

If the condition (v1 === null) returns true, the value to the left of the colon is returned, otherwise the value to the right is returned.

Our condition checks if the value in the v1 variable is equal to null and if it is, we assign the variable to the string of new value, otherwise we reassign it to its current value.

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