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

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 ==

JavaScript check if the variable exists example code

HTML example code variable is undefined or null in JavaScript.

Output:

HTML example code variable is undefined or null in JavaScript

Do comment if you have any doubts and suggestion on this topic.

Note: 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.