[javascript] JavaScript check if variable exists (is defined/initialized)

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) {

This question is related to javascript variables initialization undefined

The answer is


You want the typeof operator. Specifically:

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

Similar questions with javascript tag:

Similar questions with variables tag:

Similar questions with initialization tag:

Similar questions with undefined tag: