Skip to content

JavaScript check if a variable is defined and not empty | Example

  • by

Use typeof method with the not equal operator to check if a variable is defined and not empty in JavaScript.

if( typeof myVar !== 'undefined' && myVar != null){
    // myVar is undefined or null
}

Or syntax for checking null or undefined or empty

if (typeof value !== 'undefined' && value) {
    //deal with value'
};

JavaScript checks if a variable is defined and not empty

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    var myVar = 0

    if( typeof myVar !== 'undefined' && myVar != null ){
     console.log(myVar)
   }

 </script>

</body>
</html> 

Output:

JavaScript check if a variable is defined and not empty

Even if the value is 0, this will execute but this will pass an undefined variable.

    var myVar;

    if (myVar !== null) {
      console.log(myVar)
    }

If you don’t want it to execute when it’s 0, then set it as

if (myVar) {...}

Do 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

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