Why does `{} + []` return another result from `a = {} + []` in Javascript?

In (at least) Firefox Web Console and JSBin I get

> {} + [] 0 > a = {} + [] "[object Object]" 

Node.js returns "[object Object]" in both cases. Which behavior is correct according to the specification? If the first, why?

+8
javascript
source share
2 answers

In the browser console, when it is not preceded by = (or any other code that changes its context), {} considered as a block, not an object literal.

Since the block is empty, it does nothing, leaving + [] .

The unary plus operator converts an array to a number equal to 0 .

+15
source share

When using the operator against objects, the javascript interpreter must use the values ​​for the primitive using the valueOf method, which actually uses the internal ToPrimitive function to relay the type of the object to the internal method [[DefaultValue]].

Your example with a plus operator is a bit more complicated, because an operator can act like adding math or concatenating strings. In this case, it combines string representations of objects.

What really happens behind the scenes:

 a = {}.valueOf().toString() + [].valueOf().toString(); 

Since the array is empty, the toString method returns an empty string, so the correct result should be [object Object], which is the return value from object.valueOf () toString ().

+1
source share

All Articles