qwertymk
qwertymk

Reputation: 35274

If [] is [] and Array.prototype is [] why doesn't ([] == Array.prototype)

I'm messing around in console and saw the following:

>>> []
[]
>>> Array.prototype
[]
>>> [] == Array.prototype
false
>>> [] === Array.prototype
false

Can anyone explain this behavior? (Sounds like a good candidate for wtfjs)

Upvotes: 4

Views: 296

Answers (4)

jball
jball

Reputation: 25014

Essentially this is an extension of Raph Levien's answer but I could not fit it in a comment.

I think it's illuminating to note that

[] == [] || [] === [] //outputs false

Thus the fact that

[] == Array.prototype || [] === Array.prototype //outputs false

becomes expected. Reading the MDN Comparison Operators yields the explanation as to why all four situations evaluate to false:

  • Two objects are strictly equal if they refer to the same Object.

Equal (==) - If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.

Strict equal (===) - Returns true if the operands are strictly equal (see above) with no type conversion.

Upvotes: 1

gsnedders
gsnedders

Reputation: 5692

js> []
[]
js> Array.prototype
[]
js> [].toString == Array.prototype.toString
true
js> [].toString === Array.prototype.toString
true

That is to say, the toString method of the objects is identical. Of course, for Array.prototype.toString() (which is effectively what the second line is calling), the this object for the toString object contains no array-like properties, and hence gives [].

Upvotes: 0

Dennis Kreminsky
Dennis Kreminsky

Reputation: 2089

>>> typeof [] == typeof Array.prototype
true

Upvotes: 2

Raph Levien
Raph Levien

Reputation: 5218

In Javascript, == on arrays is pointer equality, ie only true if the both arrays are the same object. If arrays aren't pointer equal, then storing to one won't affect the other.

Upvotes: 8

Related Questions