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?