JavaScript check if a variable exists | defined/initialized example

How to check if a variable has been initialized or not in JavaScript?

Assuming the variable could hold anything (string, int, object, function, etc.)

Use The typeof operator will check if the variable is really undefined in JS.

JavaScript check if a variable exists
if (typeof variable === 'undefined') {
    // variable is undefined
}

The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared variable.

However, do note that typeof null will return “object”. We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

Using strict comparison === instead of simple equality ==

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

JavaScript check if the variable exists example code

HTML example code variable is undefined or null in JavaScript.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var num;
        if (typeof num === 'undefined' || num === null) {
            alert("variable is undefined or null")
        }
    </script>
</head>
<body>

</body>

</html>

Output:

HTML example code variable is undefined or null in JavaScript

Do comment if you have any doubts and suggestion on this 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.