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

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Brooke Cagle

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

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

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

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

If the value of the myVar variable is not equal to undefined or null, 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.

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

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

If the value to the left of the nullish coalescing operator (??) is equal to undefined or null, 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 undefined and null, it will get assigned the string new value, otherwise it will get assigned its current value.

Alternatively, you could use a ternary operator.

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

Use a ternary operator to set a variable's value if it's equal to undefined, e.g. myVar = myVar === undefined ? 'new value' : myVar;. If the condition 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 myVar = undefined; myVar = myVar === undefined ? 'new value' : myVar; console.log(myVar); // ๐Ÿ‘‰๏ธ "new value"

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

If the condition (myVar === undefined) 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 myVar variable is equal to undefined 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