Checking if a variable exists in javascript

后端 未结 7 1154
Happy的楠姐
Happy的楠姐 2021-01-31 06:58

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:

1) if ( typeof variableName !== \'undefined\' && v

7条回答
  •  执念已碎
    2021-01-31 07:52

    A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:

    • the variable is not declared (i.e., there is no var variableName in scope), or
    • the variable is declared and its value is undefined (i.e., the variable's value is not defined)

    Otherwise, the comparison evaluates to true.

    If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:

    var barIsDeclared = true; 
    try{ bar; }
    catch(e) {
        if(e.name == "ReferenceError") {
            barIsDeclared = false;
        }
    }
    

    If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:

    if (variableName !== undefined && variableName !== null) { ... }
    

    Or equivalently, with a non-strict equality check against null:

    if (variableName != null) { ... }
    

    Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

提交回复
热议问题