How to Check If Variable Exists in JavaScript

To check if a variable exists in JavaScript, use the “typeof” operator. The “typeof” operator returns a string representing the variable’s type or “undefined” if the variable is not defined.

Example 1: Check whether a variable is defined or not

if (typeof mainVar !== 'undefined') {
  console.log('mainVar exists');
} else {
  console.log('mainVar does not exist');
}

Output

mainVar does not exist

The above code checks if mainVar is defined by comparing the result of typeof mainVar to the string “undefined”.

If the result is not “undefined”, the variable exists; otherwise, it does not exist.

Remember that the typeof operator checks for the existence of a variable, not whether its value is null.

If a variable is defined but has the value null, typeof will return “object”, and the check will indicate that the variable exists.

Example 2: Check whether a variable is null or not

let data = null;

if (typeof data === null) {
  console.log("Variable is null");
}
else {
  console.log("Variable is defined and value is "
    + data);
}

Output

Variable is defined and value is null

Example 3: Falsy check

We can also check if a variable is falsy to see if it’s a falsy value, which includes undefined, null, ” (empty string), 0, NaN, or false.

let data;

console.log(Boolean(data))

Output

false

The console.log() function logs false since data is uninitialized, so it’s undefined.

And since Boolean converts any falsy value to false, that’s what we get.

You can also use the “!!” operator.

let data;

console.log(!!(data))

Output

false

That’s it!