Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 spec? If the first, why?

like image 644
Alexey Romanov Avatar asked Aug 29 '13 11:08

Alexey Romanov


2 Answers

On the browser console, when it isn't preceded by a = (or some other code that changes its context), {} is treated as a block, not an object literal.

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

The unary plus operator converts the array to a number, which is 0.

like image 183
Quentin Avatar answered Sep 22 '22 15:09

Quentin


When using an operator against objects the javascript interpreter should cast the values to primitive using the valueOf method which in fact use the internal ToPrimitive function relaying type casting to object's internal [[DefaultValue]] method.

Your example with the plus operator is a bit tricky because the operator can acts both as math addition or string concatenation. In this case it concatenates string representations of the objects.

What is really happening behind the scene is:

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

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

like image 20
user2585506 Avatar answered Sep 24 '22 15:09

user2585506