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

ぐ巨炮叔叔 提交于 2019-12-02 21:01:52

Just check for varName === undefined.

In older browsers it was possible to assign an alternate value to the global undefined variable causing that test to fail, but in ES2015+ that's now impossible.

Note that there's no way to distinguish explicitly passing undefined as a parameter from leaving the parameter out altogether other than by looking at arguments.length.

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!