typeof of boolean expression with comparison operator

≡放荡痞女 提交于 2019-12-19 21:17:23

问题


if (typeof foo !== 'undefined') {
    // Now we know that foo is defined, we are good to go.
}

The typeof evaluates to true or false based on whether the variable foo is defined or not.

But, say if foo !== 'undefined' evaluates to true, then typeof of true should evaluate to 'boolean'. Why does it evaluate to true or false?


回答1:


Because precedence rules for the typeof and inquality operators define that that expression is parsed as

(typeof foo) !== 'undefined'

For more information, see the MDN page on operator precedence. typeof is precedence 16; inquality is precedence 10. The higher precedence of typeof means that it "binds" more tightly to its operand.

By the way, why do you have undefined variables in your code?



来源:https://stackoverflow.com/questions/41618414/typeof-of-boolean-expression-with-comparison-operator

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