How to check for an undefined or null variable in JavaScript?

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You’ll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined
  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn’t yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don’t care about 0 and false, using if(obj.undefProp) is ok. There’s a common idiom based on this fact:value = obj.prop || defaultValue which means “if obj has the property prop, assign it to value, otherwise assign the default value defautValue“.Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue

Leave a Comment