What do [] + [] and [] + {} evaluate to in JavaScript?
[] + [] is the empty string and [] + {} is "[object Object]". The + operator turns both sides into strings when neither is a number, and an empty array stringifies to an empty string.
Explain it simply
The + operator has two jobs: add numbers or join strings. When you hand it two objects, JavaScript first converts each one to a primitive. Arrays and plain objects do not have a number form that makes sense, so they fall back to their string form.
- An empty array
[]becomes""(arrays join their items with commas, and there are no items). - A plain object
{}becomes"[object Object]".
Once one side is a string, + joins the two strings. So [] + [] is "" + "", which is "", and [] + {} is "" + "[object Object]".
Example
console.log([] + []); // Output:
console.log([] + {}); // Output: [object Object]
console.log([1, 2] + [3]); // Output: 1,23
console.log(typeof ([] + [])); // Output: string
console.log([] + 1); // Output: 1[1, 2] + [3] becomes "1,2" + "3", which is "1,23". And [] + 1 is "" + 1, so you get the string "1", not the number.
What to say in the interview
"Neither operand is a number, so + converts both to primitives. Arrays go through toString, which joins elements with commas, so an empty array is an empty string. A plain object gives '[object Object]'. Then + concatenates the strings. The result is always a string."
Common mistakes
- Expecting [] + [] to be 0 or an empty array. It is an empty string.
- Pasting {} + [] into a console and getting a different answer: at the start of a statement {} is read as an empty block, not an object.