JavaScript check if variable exists (is defined/initialized)

Samuel Liew picture Samuel Liew · Feb 25, 2011 · Viewed 1.7M times · Source

Which method of checking if a variable has been initialized is better/correct? (Assuming the variable could hold anything (string, int, object, function, etc.))

if (elem) { // or !elem

or

if (typeof(elem) !== 'undefined') {

or

if (elem != null) {

Answer

Jim Puls picture Jim Puls · Feb 6, 2009

You want the typeof operator. Specifically:

if (typeof variable !== 'undefined') {
    // the variable is defined
}