Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{} + [] in Javascript [duplicate]

Tags:

javascript

Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

When I type

{} + []

in the Google Chrome JavaScript console, I get

0

as a result. However, when I type

Function("return {} + []")()

I get

"[object Object]"

as a result. I would think that both operations should return the same result, as one is simply a wrapper around the other. Why do they return different results?

like image 462
Markus Roth Avatar asked Aug 13 '12 21:08

Markus Roth


People also ask

What does array [] mean in JavaScript?

In JavaScript, the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

Do you use {} for arrays?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

Can sets have duplicates JavaScript?

The Set object lets you store unique values of any type, whether primitive values or object references. you are passing new object not reference so it is allowing to add duplicate. which is actually visually similar but reference are different. Pass reference by assigning it to variable to access the added array.


1 Answers

The core reason is that {} means a different thing in a statement context { statement0; statement1 } than in an expression context ({ "property": value, ... }).

 {} + []

is a block and a unary comparison operator so the same as

{}  // An empty block of statements.
(+ [])  // Use of prefix operator +.

The other is a use of the plus operator which when used with two objects concatenates them as in

return String({}) + String([])

Since Array.prototype.toString joins the array on commas, it is similar to

return String({}) + [].join(",")

which reduces to

return "[Object object]" + "";

and finally to

return "[Object object]"
like image 190
Mike Samuel Avatar answered Oct 08 '22 12:10

Mike Samuel