The {} + [] vs [] + {} Asymmetry
What you'll learn: Why {} + [] and [] + {} produce shockingly different results in JavaScript.
The Puzzling Difference
When you write [] + {} in JavaScript, you get the string '[object Object]'. But when you flip it to {} + [], you often get 0. Wait, what? They should be symmetric, right?
Why the Asymmetry Exists
The culprit is parsing ambiguity.
When JavaScript sees {} + []:
- The parser can interpret the
{}as an empty block statement (like an empty if-block), not an object literal - That leaves
+ []standing alone - The unary
+operator coerces[]to a number - An empty array becomes
0 - Result:
0
When JavaScript sees [] + {}:
- It starts with
[], which clearly begins an expression - The
+is definitely the addition operator - Both operands coerce to strings:
''and'[object Object]' - Result:
'[object Object]'
The Context Matters
In a context where {} must be an expression (like inside parentheses or assigned to a variable), both behave consistently:
console.log({} + []); // '[object Object]' — now it's an expression!
let result = {} + []; // '[object Object]' — assignment forces expression
Key Takeaway: {} + [] often equals 0 because the parser treats {} as a code block rather than an object literal, leaving only + [] (unary plus on an empty array). Always use parentheses or assignment when you need consistent object literal behavior.