How to Check if a Javascript Variable Is undefined or null?

javascript

There are a few ways to check if a JavaScript variable is undefined or null:

  1. Using the typeof operator:
if(typeof variable === 'undefined' || variable === null) {
  // variable is undefined or null
}
  1. Using the triple-equal (===) operator:
if(variable === undefined || variable === null) {
  // variable is undefined or null
}
  1. Using the ! (not) operator:
if(!variable) {
  // variable is undefined, null, false, 0, NaN, or an empty string
}

Note that the third method checks for other falsy values in addition to undefined and null. If you only want to check for undefined and null, use one of the first two methods.

Latest Questions

javascript How to Check if a Javascript Array Includes a Given Value? javascript How to Completely Uninstall Nodejs, and Reinstall From Scratch on Mac OS X? javascript How to Map Values of a Javascript Object to a New Object Using a Function?