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

答案 1

You want the typeof operator. Specifically:

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

答案 2

The operator will check if the variable is really undefined.typeof

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

The operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.typeof

However, do note that will return . We have to be careful to avoid the mistake of initializing a variable to . To be safe, this is what we could use instead:typeof null"object"null

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}

For more info on using strict comparison instead of simple equality , see:
Which equals operator (== vs ===) should be used in JavaScript comparisons?=====