Check if a Variable Is Undefined in JavaScript

  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

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
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Variable

  • Static Variables in JavaScript