4

Why in JavaScript does {} + {} become "[object Object][object Object]" but [] + [] becomes an empty string ""? Are they not both objects in JavaScript? So why is the result of concatenation different? Any particular reason?

Why is the result not "[object Array][object Array]" for example?

Boann
  • 48,794
  • 16
  • 117
  • 146
Alireza
  • 100,211
  • 27
  • 269
  • 172

2 Answers2

5

When + is used with objects, the objects are coerced to strings and the results are concatenated.

When a plain object is turned into a string, you get [object Object]:

console.log(
  String({})
);

On the other hand, when an array is turned into a string, internally, .join(',') is called on the array, joining all elements by a comma. But if no elements exist in the array, the joined result is the empty string.

Just for the sake of curiosity (don't do this in real code!), if you deleted Array.prototype.join, String(someArr) would no longer be able to call .join, and the result would be [object Array], because the constructor of the object being turned into a string is named Array:

delete Array.prototype.join;
console.log(String([])); // Result: [object Array]
Look at the results in your browser console, not the snippet console
(because removing Array.prototype.join breaks the snippet console)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Yes, seems javascript call join function each time concatenation happens on Array which causes this not printing "[object Array][object Array]" like how it does on Object like "[object Object][object Object]", so that weirdo result happens.

Alireza
  • 100,211
  • 27
  • 269
  • 172