If [] is [] and Array.prototype is [], why not ([] == Array.prototype)

I got confused in the 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)

+4
source share
4 answers

In Javascript, == on arrays there is pointer equality, i.e. only true if both arrays are the same object. If arrays are not equal pointers, then saving to one does not affect the other.

+8
source
 >>> typeof [] == typeof Array.prototype true 
+2
source

This is essentially a Raph Levien answer extension, but I couldn’t fit it into a comment.

I think that highlights that

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

So the fact that

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

. Reading the MDN mapping operators gives an explanation of why all four situations evaluate to false:

  • Two objects are strictly equal if they belong to the same object.

Equal (==) - If two operands are not of the same type, JavaScript converts the operands and then applies a strict comparison. If any operand is a number or a logical one, the operands, if possible, are converted to numbers; 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) without type conversion.

+1
source
 js> [] [] js> Array.prototype [] js> [].toString == Array.prototype.toString true js> [].toString === Array.prototype.toString true 

That is, the toString method of the objects is identical. Of course, for Array.prototype.toString () (which is actually what calls the second line), this object for the toString object does not contain properties similar to an array, and therefore gives [] .

0
source

Source: https://habr.com/ru/post/1335933/


All Articles