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

{} + [] // -> 0 | explanation is misleading/incorrect #116

Closed EmNudge closed 3 years ago

EmNudge commented 5 years ago

explanation behind that says it's just coercion of one type plus another. What is happening there is actually a code block and a unary + which coerces the array into 0. ({} + []) would get the same as ([] + {}) understandably.

libook commented 4 years ago
+[] // -> 0
0===+[] // -> true

{}+[] // -> 0
0==={}+[] // -> false 😕WTF??

a={}+[] // -> '[object Object]' 😕WTF??
(()=>{return {}+[]})() // -> '[object Object]'
(()=>({}+[]))() // -> '[object Object]'

(╯‵□′)╯︵┻━┻

EmNudge commented 4 years ago

Yes, because {}+[] is interpreted as

{
  // a code block here
}
+[] // -> 0

although 0==={}+[] is interpreted as 0 === ({} + []). The parens force the JS engine to recognize {} as an object rather than a code block.

denysdovhan commented 4 years ago

@EmNudge could you open a PR with a fix?

denysdovhan commented 3 years ago

Fixed by #150