JavaScript's Silent Behavior with Object and Array Concatenation

JavaScript's parser has a split personality and it will silently give you a completely different result based on where you place a {}: [] + [] → "" [] + {} → "[object Object]"  {} + [] → 0 Same operands. Swapped order. Completely different result and it's not even a number anymore?? Here's what's actually happening 👇 When {} comes first, JavaScript doesn't see an object literal. It sees an empty block statement like an empty if body. So it reads the line as: {} // ← empty block (ignored) +[] // ← unary + operator on an array Unary + forces type conversion → +[] converts [] to "" → "" to 0. Result: 0 Flip it, and {} is now in expression position so JS treats it as an object. Then string concatenation kicks in. Result: "[object Object]" Same characters. Different position. Two completely different mental models activated by the parser. This is why JavaScript's implicit type coercion + context-sensitive parsing is a beautiful nightmare. The fix? Always be explicit: Number([]) // 0 String({}) // "[object Object]" Never let JS guess. It has terrible taste. 😅 Save this for your next code review, guaranteed to start a conversation. JavaScript Mastery w3schools.com

  • JavaScript coercion

This is just the tip of the iceberg. JavaScript has an entire graveyard of decisions made in 10 days back in 1995 that we're still living with in 2025. 10 days. One developer. Billions of apps. 🤝

Like
Reply

Thanks for tagging us and spreading the word! 🚀

See more comments

To view or add a comment, sign in

Explore content categories