denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.95k stars 2.55k forks source link

{} + {} #106

Closed jmdejong closed 3 years ago

jmdejong commented 5 years ago

In my browser console (firefox) {} + {} does not give "[object Object][object Object]" but Nan.

This is because the first {} is not treated as an object, but and empty code block. This does not do anything, so what remains is +{} and since an empty object can't be turned into a number that returns NaN.

This only happens when the first {} is at the start of a statement. When I do console.log({} + {}) it just prints [object Object][object Object]

Apart from the browser console you can also get this quirk using eval: eval("{} + {}") will return NaN also in the nodejs console.

lnfnunes commented 5 years ago

Not sure if this is a JS issue, looks more as Firefox Devtools implementation

Browser example: https://codepen.io/anon/pen/eXVXro

Also, I've tested on Node 10.15.3 and the problem didn't occur, which version did you test?

jmdejong commented 5 years ago

This only happens when the first {} is the first thing on a line. In the browser example you showed the line has other things first which does not cause it to be seen as empty code block.

With eval it does happen https://codepen.io/anon/pen/YgapOb

In node it doesn't happen vor me either when I just enter {} + {}, but eval('{} + {}') does give NaN (node 11.10.1).