When you say []
+ []
, JavaScript tries its best to convert the operands to numbers.
As per Addition operator's ECMA 5.1 specification,
4. Let lprim be ToPrimitive(lval).
5. Let rprim be ToPrimitive(rval).
So, first, they are tried to converted to primitive values with ToPrimitive. As Arrays are objects, JavaScript tries to retrieve the default values and use them as primitive values.
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
When DefaultValue is called without any hint, it will consider that as Number, by default.
When the [[DefaultValue]] internal method of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see 15.9.6), in which case it behaves as if the hint were String.
And the default value is retrieved like this
1. Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
2. If IsCallable(valueOf) is true then,
a. Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
b. If val is a primitive value, return val.
3. Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
4. If IsCallable(toString) is true then,
a. Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
b. If str is a primitive value, return str.
5. Throw a TypeError exception.
So, it tries to get the valueOf
of the object and tries to execute that, which returns []
and that is not a primitive value. The primitive value is defined like this
member of one of the types Undefined, Null, Boolean, Number, or String as defined in Clause 8.
Since neither of them can be converted to primitive values, they are converted to strings with toString
. Since they are empty arrays, string values are also empty strings.
That is why
console.log([] + [] === "");
# true