Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
I'm very new to JavaScript. I have a code like this :
<script type="text/javascript">
console.log( [] + {} );
</script>
which on my Google chrome browser logs :
[object Object]
It looks wired to me! And doing something like this :
<script type="text/javascript">
console.log( {} + {} );
</script>
does produce :
[object Object][object Object]
What is exactly happening over here in both the cases? How come [],{} adding these two results in a array of objects?
Thanks in advance.
When you use the + operator with non-numbers, you're doing string concatenation, and so the operands are converted to strings. An empty array becomes an empty string because it's an implicit call to join, and with no entries, join returns an empty string; an object becomes "[object Object]".
So
console.log( [] + {} );
...comes down to
console.log( String([]) + String({}) );
...which comes down to
console.log( "" + "[object Object]");
You are adding object to array - so it is put on the end. When you apply + with 2 objects, only operation making sense is to convert to strings and concatenate it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With