There is a statement +[[]] + [[]]
. Console returns "0" (a string).
When a statement is +[[]]
console returns 0 (a number).
How come the first one returns a string if +0+0
is 0?

- 226,338
- 43
- 373
- 367

- 87
- 1
- 6
-
2The first one is a _unary_ plus, the second one a _binary_ one. Don’t confuse those. – Sebastian Simon Sep 28 '16 at 19:17
-
javascript is weird. Would that answer your question? :) – Sergio Tulentsev Sep 28 '16 at 19:20
-
@pro: where did the string come from? – Sergio Tulentsev Sep 28 '16 at 19:20
2 Answers
The syntax tree here looks like
+
/ \
/ \
+ [ ]
| |
| |
[ ] [ ]
|
|
[ ]
That is, the left hand side operand of the binary +
is the result of the unary +
operation, and the right-hand side operand is the result of the [[]]
expression.
The left-hand side is a number, per the runtime semantics of the unary +
operator operator, which invokes ToNumber.
The right-hand side is an object, which is cast to a string primitive by ToPrimitive (by way of invoking the object's toString
method) in step 9 of the evaluation of the +
operator. In the case of arrays, toString
returns the stringified form of the array's contents joined by commas, which in this case is the empty string.
You can verify this by overriding toString
on some object and seeing the changed result:
var a = [];
a.toString = function() { return "foo"; };
console.log(0 + a);
This will produce "0foo"
.

- 112,806
- 17
- 235
- 239
+[[]]
- there is unary operator.
The Unary + operator converts its operand to Number type. The Unary - operator converts its operand to Number type, and then negates it.
Your expression is obviosly +[[]]
plus [[]]
where '[[]]' are converted to an empty string due to binary +
operator.
And therefore is 0 + '' = '0'

- 1,746
- 1
- 16
- 20