2

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.

Community
  • 1
  • 1
Ant's
  • 13,545
  • 27
  • 98
  • 148

3 Answers3

11

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]");
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
1

[] is an empty array, which is converted to a string (because of the concatenation operator). {} is an empty Object.

zessx
  • 68,042
  • 28
  • 135
  • 158