{} + [] is not 0


The thing to keep in mind about coercing objects like arrays to primitives, is they usually become strings first. So coercing an empty object to a number goes like this:

+ {};
// "[object Object]"
// NaN

But the toString for an array happens to be capable of producing a number of valid number strings. It converts each element to a string, and then joins them with commas. That means for single element arrays, it effectively just drops the array. And for empty arrays those become empty strings which become 0. For reasons.

+ [1, 2, 3];
// "1,2,3"
// NaN

+ [4];
// "4"
// 4

+ []:
// ""
// 0

As for undefined and null. Yeah. That’s just what the spec says to do, so that’s how it works.

Comments are closed.