The use of undefined variables in if-statements

前端 未结 6 1745
别跟我提以往
别跟我提以往 2021-02-05 10:06

This snippet results in a JavaScript runtime error: (foo is not defined)

if (foo) {
    // ...
}

I have to define foo

6条回答
  •  清歌不尽
    2021-02-05 10:34

    I sense you are asking because you are aware that javascript seems to allow undefined variables in some situations (ie no runtime errors) and not in others.

    The reasoning is as follows: javascript always throws an error on checking undefined variables, but never throws an error on checking undefined properties, as long as you only use one level of indirection.

    Example:

    // throws runtime error
    if(foo) {
        // ...
    }
    
    // does not throw runtime error
    if(window.foo) {
        // ...
    }
    
    // does not throw runtime error
    var obj = {};
    if(obj.foo) {
        // ...
    }
    
    // throws runtime error
    if(obj.foo.bar) { // going two levels deep, but foo is undefined
        // ...
    }
    

    Hope that clears it up a bit.

提交回复
热议问题