Reassign A Variable If Null Or Undefined In JavaScript

Today I will share with you the simplest ways to reassign a variable if Null or Undefined in JavaScript. So, please read this article to the end to get more information.

Reassign a variable if Null or Undefined in JavaScript

First of all, we will find out when a variable is null or undefined in JavaScript. Check out the code below to get more information.

Code example:

let learnshare1;
console.log(learnshare1); // undefined

let learnshare2 = null;
console.log(learnshare2); // null

Output:

undefined
null

So you know when a variable is null or undefined, here we will start to learn the methods to reassign a variable if null or undefined in JavaScript.

Using the If check

In this method, we can check if a variable is null or undefined by using the If - else method. If a variable is null or undefined, you will reassign a variable. Follow the code:

Code example:

let learnshare1;

// Check if undefined
if (learnshare1 === undefined) {
    learnshare1 = "Updated successfully"; // Reassign a variable
    console.log(learnshare1);
} else {
    console.log("Not reassign");
}

let learnshare2 = null; // Initial a variable

// Check if null
if (learnshare2 === null) {
    learnshare2 = "Updated successfully"; // Reassign a variable
    console.log(learnshare2);
} else {
    console.log("Not reassign");
}

Output:

Updated successfully
Updated successfully

Otherwise, you can shorten the code to make it clean code as follows:

let learnshare;

// Check if null or undefined
if (learnshare === null || learnshare === undefined) {
    learnshare = "Updated successfully"; // Reassign a variable
    console.log(learnshare);
} else {
    console.log("Not reassign");
}

Output:

Updated successfully

Using the logical nullish assignment

Here, we will use a logical nullish assignment operator to reassign a variable if null or undefined. 

First, we create a variable with the name learnshare, and then we will use a logical nullish assignment operator to assign a value for a learnshare variable. If a learnshare variable is null or undefined, it will not assign and keep value begin. Check out the code example below:

Code example:

let learnshare; // Initial a variable

// Use logical nullish assignment to check null or undefined and assign
learnshare ??= "updated successfully"
console.log(learnshare)

Output:

updated successfully

Summary

So, above are all the methods that I share with you to reassign a variable if Null or Undefined in JavaScript. If you have any questions, please leave a comment below. Thanks for reading, and good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *