How to Check If Variable Exists in JavaScript

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

Example

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.

Leave a Comment