Use typeof to check (determine) if the variable is defined or not in JavaScript. The typeof
operator can evaluate even an undeclared identifier without throwing an error.
if(typeof variable === "undefined"){
/* It is undefined */
}
To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:
if ('undefined' !== typeof x) {
}
JavaScript checks if the variable is defined
Simple example code. The typeof operator, unlike the other operators, doesn’t throw a ReferenceError exception when used with an undeclared symbol
<!DOCTYPE html>
<html>
<body>
<script>
var variable = "Hello";
if (typeof variable != 'undefined') {
console.log(variable)
}
</script>
</body>
</html>
Output:
More code
<script>
var x;
var y = 10;
if(typeof x !== 'undefined'){
// this statement will not execute
alert("Variable x is defined.");
}
if(typeof y !== 'undefined'){
// this statement will execute
alert("Variable y is defined.");
}
// Attempt to access an undeclared z variable
if(typeof z !== 'undefined'){
// this statement will not execute
alert("Variable z is defined.");
}
/* Throws Uncaught ReferenceError: z is not defined,
and halt the execution of the script */
if(z !== 'undefined'){
// this statement will not execute
alert("Variable z is defined.");
}
/* If the following statement runs, it will also
throw the Uncaught ReferenceError: z is not defined */
if(z){
// this statement will not execute
alert("Variable z is defined.");
}
</script>
Do comment if you have any doubts or suggestions on this JS variable topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version