How to Check if a Variable Is Undefined in JavaScript
-
Directly Compare a Variable With
undefined
to Check Undefined in JavaScript -
Comparison With
void 0
to Check Undefined in JavaScript -
Use the
typeof
Operator to Check Undefined in JavaScript
This tutorial introduces how to check if a variable is undefined in JavaScript.
A variable is called undefined
if it is declared without being assigned an initial value. Below are multiple ways we can do this in JavaScript.
Directly Compare a Variable With undefined
to Check Undefined in JavaScript
var x;
if (x === undefined) {
text = 'x is undefined';
} else {
text = 'x is defined';
}
console.log(text);
Output:
"x is undefined"
Here we take an undefined variable name and compare it directly with undefined
without using any function or anything. But this method throws an error if we try to compare a variable that is not declared.
Comparison With void 0
to Check Undefined in JavaScript
var abc;
console.log(abc === void 0);
Output:
true
Here we take an undefined variable name and compare it with void 0
. This method also throws an error if we try to compare a variable that is not declared.
Use the typeof
Operator to Check Undefined in JavaScript
This operator returns a string that tells about the type of the operand. If the value is not defined, it returns a string undefined
.
var abc;
console.log(typeof abc === 'undefined')
Output:
true
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedInRelated Article - JavaScript Variable
- How to Access the Session Variable in JavaScript
- How to Check Undefined and Null Variable in JavaScript
- How to Mask Variable Value in JavaScript
- Why Global Variables Give Undefined Values in JavaScript
- How to Declare Multiple Variables in a Single Line in JavaScript
- How to Declare Multiple Variables in JavaScript