JavaScript + Empty Array + Object
This is a daily Javascript challenge from the CodeShot archive. Practice your knowledge of Object Array Addition and improve your technical interview readiness.
console.log([] + {})
Detailed Explanation
# The Weird World of JavaScript Type Coercion: What happens when you add an array to an object?
If you've spent any time in a JavaScript codebase, you've probably encountered a moment where the language does something that feels completely illogical. One of the classic "gotcha" questions in technical interviews is this one:
At first glance, you might think it returns an empty array, an object, or maybe NaN. But the actual result is "[object Object]".
If that sounds like nonsense, you're in good company. To understand why this happens, we have to look at how JavaScript handles type coercion.
Why This Question Matters
This isn't just a trivia question to trip up juniors in interviews. It touches on the core of how JavaScript handles different data types when they interact.
JavaScript is a loosely typed language. When you use an operator like + on two different types, JS doesn't just throw an error. Instead, it tries to be "helpful" by converting the operands into a common type—usually a string—so it can complete the operation. This process is called coercion.
Understanding this is the difference between a developer who just copies snippets from StackOverflow and one who actually knows why their state is suddenly becoming a string in a React component.
Understanding the Code
Let's break down [] + {} step-by-step.
The + operator in JavaScript has two primary jobs: addition (numbers) and concatenation (strings). When the engine sees +, it checks the types of the values on either side. If either side is a string, or if it *can* be converted to a string, JS will lean toward concatenation.
Here is the internal logic the engine follows:
1. The Array ([]): An empty array is an object. To use it with a + operator, JS needs to convert it to a primitive. It calls the internal toString() method. For an empty array, [].toString() returns an empty string: "".
2. The Object ({}): Similarly, the empty object needs to be converted to a primitive. It calls its own toString() method. By default, all plain objects in JS inherit a toString() method from Object.prototype that returns the string "[object Object]".
3. The Operation: Now the expression is effectively "" + "[object Object]".
Since we are adding two strings, JavaScript simply concatenates them. The result is "[object Object]".
Finding the Correct Answer
If this were a multiple-choice question, the options might look like this:
A) "[object Object]"
B) "{}"
C) NaN
D) TypeError
The answer is Option A.
Why not the others?
- B is wrong because the array doesn't "absorb" the object; they are both converted to strings first.
- C is wrong because NaN (Not-a-Number) usually occurs when a mathematical operation fails (like undefined + 5), but string concatenation always succeeds.
- D is wrong because JS is designed to avoid crashing at all costs. It would rather give you a weird string than throw a TypeError.
Common Mistakes Developers Make
The biggest mistake is assuming that [] behaves like a "nothing" value. In some languages, an empty collection might be treated as falsy or null. In JS, an array is an object, and its string representation is a specific behavior of the language.
Another common trip-up is the order of operations. If you swap them:
{} + []
In a browser console, this might actually give you 0 or "[object Object]" depending on whether the engine interprets the {} as an empty block or an object literal. This is why you should almost always wrap your objects in parentheses ({} + []) if you're testing these quirks, to ensure the engine treats the curly braces as an object.
Real-World Usage
You will likely never write [] + {} in a production app on purpose. However, this logic pops up constantly in real engineering work:
1. Template Literals: When you do Value: ${myArray} , JS is doing exactly what we described above. If myArray is empty, it inserts an empty string. If it's [1, 2], it inserts "1,2".
2. Accidental String Conversion: Imagine you have a state variable that is supposed to be an object, but due to a bug, it gets concatenated with a string. You'll see "[object Object]" appear in your UI. When you see that string, you immediately know you're trying to render a raw JavaScript object instead of a property of that object.
3. Logging: Using console.log("Data: " + data) is an old habit. If data is an object, you get the useless "[object Object]". This is why modern developers use console.log("Data:", data) (comma instead of plus), which tells the console to log the actual object structure rather than coercing it to a string.
Key Takeaways
- The + operator triggers type coercion when dealing with mixed types.
- Arrays and Objects are converted to primitives via their toString() methods.
- An empty array becomes an empty string; a plain object becomes "[object Object]".
- To avoid these "magic" conversions in your code, use strict equality (===) and avoid using + for anything other than numbers or explicit string concatenation.
Why this matters
Understanding Object Array Addition is crucial for passing technical interviews. In real-world applications, this concept often leads to subtle bugs if not handled correctly. For more details, you can always refer to the official MDN Documentation.