Skip to content

JavaScript check undefined | typeof and equality operator

  • by

If the variable declared without assigned any value then its initial value is undefined. You can use the typeof operator or if statement to check the value undefined in JavaScript.

Undefined variable

var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

Example of JavaScript check undefined

HTML example code of comparing a variable using if statement. It works with modern browsers.

Use the equality operator (==)

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var name_first;

    if(name_first === undefined) {
        alert('Variable "name_first" is undefined.');
    }

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

Output:

Example of JavaScript check undefined

Using typeof

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var name_first;

    if(typeof name_first === 'undefined') {
        alert('Variable "name_first" is undefined.');
    }

    </script> 
      
    
</body> 
  
</html> 
JavaScript check undefined typeof

Q: How to handle undefined in JavaScript

Answer: You can check the fact with.

if (typeof(jsVar) == 'undefined') {
  ...
}

Q: How to determine if the variable is checked if undefined or 0 in JavaScript?

Answer: To check if a variable is undefined or null you can use the equality operator == or strict equality operator === (also called identity operator).

<script>
if(typeof comment === 'undefined') {
        alert('Variable "comment" is undefined.');
    } else if(comment === null){
        alert('Variable "comment" is null.');
    }
</script>

Do comment if you have any doubts, questions or suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
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