How dangerous is it in JavaScript, really, to assume undefined is not overwritten?

后端 未结 8 998
Happy的楠姐
Happy的楠姐 2020-11-27 04:36

Every time anyone mentions testing against undefined, it\'s pointed out that undefined is not a keyword so it could be set to \"hello\", so you sho

8条回答
  •  伪装坚强ぢ
    2020-11-27 04:40

    First of all, if your code breaks it's probably not because some other developer out there "is trying to be a jerk" as you put it.

    It's true that undefined is not a keyword. But it is a global level primitive. It was intended to be used like this (see "undefined" at developer.mozilla.org):

    var x;
    if (x === undefined) {
        // these statements execute
    }
    else {
        // these statements do not execute
    }
    

    The common alternative to that (also from MDN) and in my opinion the better way is:

    // x has not been declared before
    if (typeof x === 'undefined') { // evaluates to true without errors
        // these statements execute
    }
    
    if(x === undefined){ // throws a ReferenceError
    
    }
    

    Which has a couple of advantages, the obvious one (from the comments) is that it does not trigger an exception when x is not declared. It's also worth noting that MDN also points out that it is important to use === over == in the first case because:

    var x=null;
    if (x === undefined) {
        // this is probably what you meant to do
        // these lines will not execute in this case
    }
    else if (x == undefined) {
        // these statements will execute even though x *is* defined (as null)
    }
    else {
        // these statements do not execute
    }
    

    This is another often overlooked reason why it is probably better to just use the second alternative in all cases.

    Conclusion: It's not wrong to code it the first way, and certainly not dangerous. The argument you've seen that you use as an example against it (that it can be overwritten) is not the strongest argument for coding the alternative with typeof. But using typeof is stronger for one reason specifically: it doesn't throw an exception when your var is not declared. It could also be argued that using == instead of === is a common mistake in which case it's not doing what you expected it to. So why not use typeof?

提交回复
热议问题