How to Check if the Variable is Undefined
This tutorial provides the method of checking whether the type of the variable is undefined. Read about the differences between undefined and “undefined”.
It is possible to check whether a variable is defined or not in JavaScript with the typeof operator which returns a string telling the type of the operand.
Do the following to check if the value's type is "undefined":
Check if the value's type is "undefined"
To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === .
⚠️ Note: Direct comparison (=== or ==) will throw a ReferenceError if the variable is undeclared. Use typeof to safely check undeclared variables.
If you declare a variable but do not assign a value, it is automatically assigned undefined. Thus, if you try to display the value of such a variable, the word "undefined" will be displayed.
You can also check The Difference Between Null and Undefined in JavaScript snippet.
undefined vs “undefined”
There are two ways of determining whether a variable is undefined: by value or by type. If you check by value, you verify whether the variable holds a specific value. In the case of undefined, the variable doesn't have a value but still exists.
Checking the type is done with the typeof operator. Note that variable === "undefined" checks if the variable's value is the string "undefined", not its type.