If you open your JS console and type in [] + {} === {} + []
it tells you it's true.
I don't understand why this is. I attempted to look up at how it's parsed.
For [] + {}
the +
here is the addition operator as operands are both literals. LHS doesn't yield a number through .valueOf()
so it performs string concatenation using .toString()
on both operands giving us ""
+ "[object Object]"
For {} + []
the {}
is an empty code block and is 'ignored', the +
operator here is parsed as the unary plus operator, it converts its operand to a Number. Empty arrays converted to a number become 0
So this is appears to be "[object Object]" === 0
which surely should be false?.
The identity operator checks if the two operands are equal without type conversion. I can't see how this ever coud be true. What part of the story am I missing?
Edit:
I see if you type ({} + [])
it parses it as an empty object making the RHS equal to "[object Object]". I looked this up and ( )
is the grouping operator. So perhaps this has something to do with this?
This is not a duplicate of What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?. Answer bullet points 1 === 2 should NOT be true.