Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[] + {} is equal to [object Object], in Javascript? How? [duplicate]

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.

like image 520
Ant's Avatar asked Jul 09 '26 15:07

Ant's


2 Answers

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]");
like image 172
T.J. Crowder Avatar answered Jul 11 '26 11:07

T.J. Crowder


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

like image 29
Konstantin Pribluda Avatar answered Jul 11 '26 09:07

Konstantin Pribluda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!