Skip to content

JavaScript check if variable has value

  • by

To check if a variable has a value in JavaScript, you can use a conditional statement such as an if statement to check if the variable is not undefined, null, or empty.

let myVariable;

if (myVariable) {
  // This code will not execute because myVariable does not have a value
}

myVariable = "Hello, world!";

if (myVariable) {
  // This code will execute because myVariable has a value
}

In the first if statement, the code inside the curly braces will not execute because myVariable does not have a value yet. In the second if statement, the code inside the curly braces will execute because myVariable has a value.

JavaScript checks if the variable has a value example

Simple example code.

<!DOCTYPE html>
<html>
  <body>    
    <script>
    let myVariable;

    // Check if myVariable has a value
    if (myVariable) {
        console.log("myVariable has a value");
    } else {
        console.log("myVariable does not have a value");
    }

    myVariable = "Hello, world!";

    // Check again if myVariable has a value
    if (myVariable) {
        console.log("myVariable has a value");
    } else {
        console.log("myVariable does not have a value");
    }


    </script>
  </body>
</html>

Output:

JavaScript check if variable has value

If you want to check specifically for a null or undefined value, you can use a stricter comparison operator such as ===:

let myVariable;

if (myVariable === null || myVariable === undefined) {
  // This code will execute because myVariable does not have a value
}

myVariable = "Hello, world!";

if (myVariable === null || myVariable === undefined) {
  // This code will not execute because myVariable has a value
}

Comment if you have any doubts or suggestions on this Js variable topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading