JavaScript: How to check if variable exists

JavaScript

What is the correct way to check if an variable exists / is defined in JavaScript? I wrote this example statements. But which method is the best one?

if (myVariable) {
  //do something
}

if (myVariable !== null) {
  // do something
} 

if (typeof(myVariable) !== 'undefined') {
  // to something
}
Programming Software Question created: 2020-08-15 06:52 peon

12

Mostly you can use this simple statement:

if (myVariable) {
  //do something
}

It will check for:

  • false, boolean.
  • an empty string, ‘’
  • undefined, if the variable was not defined and its value is “undefined”.
  • null, if its null.
  • 0, number zero. 
  • NaN, not a number.

This statement covers all cases and its the correct and easiest way to check if an variable exists or holds one of the listed values. 

You could also use the explicit check for “undefined” like this:

if (typeof(myVariable) !== 'undefined') {
  //do something with "myVariable", its defined and available.
}

The “not null” check:

if (myVariable !== null) {
  // do something
} 
answered 2020-08-15 07:04 cleaner

4

An short an easy way to check if an variable is defined or is not defined:

if (typeof(aVariable) === "undefined") {
  // the variable is undefined
}

I use this logic in the most cases when checking for an undefined variable in JavaScript.

answered 2020-08-15 07:11 Peterson