How to Check If a Variable is “undefined” in JavaScript

To check if a variable is “undefined” in JavaScript, use the “strict equality operator(===)” or “typeof operator” along with the “strict equality (===)” operator.

Method 1: Using the strict equality operator(===)

In JavaScript, the easy way to check if a variable is “undefined” is by using the “strict equality operator”(===).

Example

let myVar;

if (myVar === undefined) {
  console.log('myVar is undefined');
} else {
  console.log('myVar is defined');
}

Output

myVar is undefined

In this example, myVar is declared but not assigned a value, so its value is undefined.

Method 2: Using the typeof operator with === operator

You can use the typeof operator in JavaScript to check if a variable is undefined. The typeof operator returns a string suggesting the type of the operand.

Example

let data = undefined;

if (typeof (data) === undefined) {
  console.log('Yes in fact it is undefined');
}

Output

Yes in fact it is undefined

The typeof operator “returns the string, indicating a type of unevaluated operand”.  The operator returns a data type of its operand as a string.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.