0

I have an undefined variable and I check it in a string concat:

var undefinedVariable = undefined;
console.log("foo" + undefinedVariable === undefined ? "bar" : undefinedVariable.toString() );

Considering that undefinedVariable is undefined, undefinedVariable.toString() is an unreachable code. However, I get this error:

Uncaught TypeError: Cannot read property 'toString' of undefined(…)

The strange thing is if I remove "foo" at the start of console.log, then the code works fine.

console.log(undefinedVariable === undefined ? "bar" : undefinedVariable.toString() );

I have tested in chrome and firefox and I get the same result so probably it is not a bug. Is there any explanation why JS engines try to run the unreachable part?

4

1 回答 1

3

这是因为Operator Precedence。(+连接运算符)的优先级高于?:(三元运算符)。因此,您需要将三元条件包含在其中(),因为它与+(concatenation operator) 一起使用,而左侧不再是undefined. 利用:

console.log("foo" + (undefinedVariable === undefined ? "bar" : undefinedVariable.toString()) );

您需要告诉 JavaScript 引擎undefinedVariable单独评估,不要同时加入"foo"andundefinedVariable和评估。

var undefinedVariable = undefined;
console.log("foo" + (undefinedVariable === undefined ? "bar" : undefinedVariable.toString()) );

以上给了我:foobar

输出

于 2016-06-07T17:34:41.180 回答