The built-in toPrimitive() function is called when an object is converted to its original type.
- Is already a primitive type, returns this value directly,
- Call the valueOf() method, return the value if the result is the original value,
- Call the toString() method, return the value if the result is the original value,
- Otherwise, an error is thrown.
Both an empty array and an empty object perform the above steps when casting, and neither of them is a primitive value. Therefore, valueOf() is called directly to simply return the original valueOf both of them.
The toString() method is then called. The result of an empty array is an empty string, and the result of an empty object is the string [object object].
Finally, the + prefix converts the element to type number, the empty string ‘ ‘to 0, and the string ‘[object object]’ to NaN.