Javascript tricky question: 0undefined | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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????

25th Sep 2020, 5:45 PM
Prof. Dr. Zoltán Vass
6 Answers
+ 4
Apparently you can concatenate numbers, strings, objects, null and undefined in JS. Reference: https://masteringjs.io/tutorials/fundamentals/string-concat
25th Sep 2020, 6:19 PM
Avinesh
Avinesh - avatar
+ 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.
25th Sep 2020, 6:46 PM
Ipang
+ 2
0+undefined becomes a string
25th Sep 2020, 6:06 PM
Alessandro Palazzolo
Alessandro Palazzolo - avatar
+ 1
Alessandro Palazzolo 0 + undefined is evaluated as NaN, not as a string - try it!
25th Sep 2020, 6:52 PM
Prof. Dr. Zoltán Vass
+ 1
Ipang Thank you for the clear explanation! My only question is why 0 + undefined is evaluated to 0undefined.
25th Sep 2020, 6:55 PM
Prof. Dr. Zoltán Vass
+ 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
25th Sep 2020, 6:59 PM
Prof. Dr. Zoltán Vass