ES2015/2016 way of 'typeof varName === 'undefined`?

前端 未结 2 1755
梦毁少年i
梦毁少年i 2021-01-31 13:41

I\'m wallowing in ES2015+ luxury with a few projects right now and am wondering whether I can get rid of the much hated crutch to check for undefined in the new won

2条回答
  •  故里飘歌
    2021-01-31 14:11

    The only case where typeof varName === 'undefined' is useful is when you don't know whether the variable varName has been declared.

    And IMO if you don't know whether your variables are declared, your code has serious problems.

    In other cases you have better options:

    • varName === void 0

      This will detect whether varName is undefined.

      void is an operator which receives an argument (you can use whatever instead of 0), and returns undefined.

    • varName === undefined

      This should detect whether varName is undefined.

      However, be aware the global undefined could have been overwritten (before ES5) or shadowed with another value. Therefore I prefer void, which is also shorter.

    • varName == null

      This will detect whether varName is undefined or is null.

    • !varName

      This will detect whether varName is falsy (undefined, null, 0, empty string, NaN, false).

提交回复
热议问题