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

后端 未结 8 918
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:53

    You can use undefined in your code when coding for browsers supporting ECMAScript 5.1 as it is immutable according to the language specification.

    Also see this compatibility table or this caniuse ECMAScript 5 to see that all modern browsers (IE 9+) have implemented immutable undefined.

    0 讨论(0)
  • 2020-11-27 04:58

    There's a simple solution to that: compare against void 0 which is always undefined.

    Note that you should avoid == as it may coerce the values. Use === (and !==) instead.

    That said, the undefined variable may be set by error if someone writes = instead of == when comparing something against undefined.

    0 讨论(0)
提交回复
热议问题