When we generally talk about the + operator, the tricky problem we think about is: Why does 1 + 2 + "3" result in "33" whereas "1" + 2 + 3 = "123"?
But do we ever stop and think — can we add arrays with numbers? 🤯
Sounds silly, but what really happens when JavaScript encounters such an expression?
It all depends on how JavaScript parses code. You see, when you write [] + 1, you don’t get an error. Instead, you get the result "1". Let’s understand how and why this happens.
When JavaScript encounters a non-primitive value in an expression, it tries to convert it to a primitive using its internal ToPrimitive algorithm. First, it calls .valueOf(), and if that doesn't return a primitive, it uses .toString(), which for an empty array, gives "". So effectively [] + 1 becomes "" + 1, which gives the string "1"due to string concatenation.
But that’s not all. Get this, ({}).toString() returns "[object Object]", so when you add [] + {}, the result is "[object Object]". BUT 😏 when you do {} + [], you get…
… a big fat 0.
Why? Again, it’s all about how JS parses code. In this case, JavaScript sees {} as an empty code block, not an object. So it interprets +[] as a unary plus operation, which coerces the empty array into 0. Want the original result? Wrap it in parentheses ({} + []) = "[object Object]".
I’ll be sharing a follow-up post soon with more mind-bending JavaScript edge cases.
How did you find this one? Helpful, confusing, or just plain wild? Drop your thoughts in the comments 👇
Top comments (0)