Ashwin Krishnamurthy
Ashwin Krishnamurthy

Reputation: 3758

Adding arrays and objects in javascript produces an error

I get these outputs when the following operations are carried out

var t = {} + {}; // Alerts [object Object][object Object]
t = {} + 1 //Alerts [object Object]1
t = {} + "hello" //Alerts [object Object]hello
t = {} + function(){} //Alerts [object Object]function(){}
t = {} + [] //Alerts [object Object]

In the last case alone it alerts [Object object] shouldn't it display [object Object][object Object] for this too?

Tested in Firefox12.0.

Upvotes: 4

Views: 105

Answers (1)

Jon
Jon

Reputation: 437336

No, because the second part of the output is the stringified form of the empty array []. Arrays are stringified as a comma-separated list of stringified values, so the empty array stringifies to the empty string. You can confirm this with console.log([] + "" === "").

Therefore, {} + [] results in the equivalent "[object Object]" + "".

Upvotes: 7

Related Questions