Why is Array + Array equal to an empty string?

I saw this pretty funny screencast yesterday about some oddities in languages ​​like Ruby and Javascript, and the guy shows that:

[] + [] -> ""  // returns empty string

not very obvious ...

I decided to go to the ECMAscript language specification to get more information. I started by implementing an operator +(p .75) which says:

11.6.1 Add (+) operator

The addition operator performs either string concatenation or numeric padding.
The output of AdditiveExpression: AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue (lref).
3. Let rref be the result of evaluating the multiplicative expression.
4. Let rval be GetValue (rref).
5. Let lprim be ToPrimitive (lval).
6. Let rprim be ToPrimitive (rval).
7. If Type (lprim) is a String or Type (rprim) is a String, then a. Return the string that is the result of concatenating ToString (lprim) and then ToString (rprim)
8. Return the result of applying the add operation to ToNumber (lprim) and ToNumber (rprim). See Note below 11.6.3.

1. ToPrimitive 5 6. ToPrimitive . ECMAScript, Date, , ; Date , . - - .

2 7 3 (11.8.5), .

, 7 - /, , , ...

- ?


, , :

[] + {} -> [object Object]
{} + [] -> 0
+5
1
  • lprim ToPrimitive (lval).
  • rprim - ToPrimitive (rval).

ToPrimitive :

O [[DefaultValue]] , , Number, O (. 15.9.6), , .

, , Number:

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:
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.

[].valueOf() , [].toString(), "".

, , .toString [object Object], .toString .join(",")


{} + []

{} , . , :

{}
+[]; //Same as +[] ( Number([]) ) which is 0

{} + [],

({}) + [] ({} + [])

:

{} ! [] //false
({}) ! [] //SyntaxError
+7

All Articles