Use typeof in if statement expression to check variables not undefined in JavaScript. In JavaScript, null
is an object. There’s another value for things that don’t exist, undefined
.
Where typeof
will treat an undeclared variable and a variable declared with the value of undefined
as equivalent.
But, to check if a variable is declared and is not undefined
:
if (yourvar !== undefined) // Any scope
Previously, it was necessary to use the typeof
operator to check for undefined safely because it was possible to reassign undefined
just like a variable. The old way looked like this:
if (typeof yourvar !== 'undefined') // Any scope
Source: stackoverflow.com
JavaScript if not undefined
Simple example code check if a JavaScript variable is NOT undefined. Remember, undefined is an object in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
var msg = "Hi";
if(typeof msg !== "undefined")
{
alert("Hi. Variable is defined.");
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS if statement topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version