0
Javascript tricky question: 0undefined
var y = 0; if (function f(){}) { y += typeof f; } console.log(y); // 0undefined I found this snippet in a SL quiz but don't understand the output. Function f() is an IIFE that runs without calling it and executes the third line. Here y = 0 and typeof f = undefined. However, 0 + undefined should be NaN. So why is the output 0undefined????
6 Respuestas
+ 4
Apparently you can concatenate numbers, strings, objects, null and undefined in JS.
Reference: https://masteringjs.io/tutorials/fundamentals/string-concat
+ 4
It seems that a function declaration (treated as logical expression) is evaluated as truthy, hence, the `if` conditional body block gets processed.
But 'f' does not actually get declared as a function, because the "declaration" was only used as an evaluable expression (branch condition) for the `if` conditional. That's why it is 'undefined' inside the `if` conditional block.
'f' is not an IIFE either, verify by putting an instruction in its body e.g. an alert box, it won't be invoked.
That's how I see it ... could be wrong though.
+ 2
0+undefined becomes a string
+ 1
Alessandro Palazzolo 0 + undefined is evaluated as NaN, not as a string - try it!
+ 1
Ipang Thank you for the clear explanation! My only question is why 0 + undefined is evaluated to 0undefined.
+ 1
In the meantime, I figured out the solution: typeof always returns a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof