How to Check if a Variable Is Undefined in JavaScript

Harshit Jindal Feb 02, 2024
  1. Directly Compare a Variable With undefined to Check Undefined in JavaScript
  2. Comparison With void 0 to Check Undefined in JavaScript
  3. Use the typeof Operator to Check Undefined in JavaScript
How to Check if a Variable Is 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 avatar Harshit Jindal avatar

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.

LinkedIn

Related Article - JavaScript Variable