0

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?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367

2 Answers2

3

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".

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

+[[]] - 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'

layonez
  • 1,746
  • 1
  • 16
  • 20