Use the in
operator for a more robust check of variables if undefined or not in JavaScript. Or you can use typeof
like this:
if (typeof something != "undefined") {
// ...
}
JavaScript check if undefined
Simple example code to finding out whether a variable has been declared regardless of its value, using the in operator
is the safest way to go.
// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"
If you are interested in knowing whether the variable hasn’t been declared or has the value undefined
, then use the typeof
operator, which is guaranteed to return a string:
<!DOCTYPE html>
<html>
<body>
<script>
if (typeof myVar == 'undefined')
{
alert("Hello variable")
}
</script>
</body>
</html>
Output:

Source: stackoverflow.com
Do comment if you have any doubts or suggestions on this JS if the topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version

Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.