If both [0] == 0 and 0 == [[0]] are true, then why is [0] == [[0]] false?

We all know that javascript makes funky transformations when testing for equality, but what exactly happens under the hood?

> [0] == 0 true > 0 == [[0]] true > [0] == [[0]] false 

Yes, I was naive to expect transitivity from the == operator.

+6
source share
3 answers

[0] == 0 and 0 == [[0]] compares the primitive value with the object and thus type conversion will be performed . In both cases, [0] and [[0]] will eventually be converted to a primitive value of 0 .

This is defined in steps 8 (and 9) of the Abstract Equation Comparison Algorithm :

  1. If type (x) is either a string or a number, and type (y) is an object,
    returns the comparison result x == ToPrimitive (y).

However, [0] === [[0]] compares two objects, and two different objects are never equal to each other:

1st Return true if x and y refer to the same object. Otherwise, return false.


Here is a slightly simpler example demonstrating that free comparison is not transitive:

 " " == 0 // true "\n" == 0 // true " " == "\n" // false 

The first two comparisons perform type conversion (string to number), the latter is not performed, and the values โ€‹โ€‹of both strings are different.

+7
source

Your first 2 examples implicitly convert arrays to strings, and then compare them to 0 :

 var a = [0].toString(); // "0" var b = a == 0 // "0" == 0; // true 

The last example does not display arrays, it just compares the identifiers of arrays. Obviously they do not match, so false returned.

The extra level of depth that you have in some of these arrays doesn't matter in your examples:

 [0] == [0] // false, they're not the same array. 0 == [[[[0]]]] // true, [[[[0]]]].toString() === "0", "0" == 0 

Like @JanDvorak mentioned in a comment on @KooiInc , behind the scenes JS does not use toString for this conversion. However, in concept, this is what happens.

+2
source

Behavior complies with JavaScript. Abstract equality comparison algorithm.

  • Comparison [0] == 0 - types of operands differ

Corresponds to case 9 of algo : Type (x) is an object and type (y) is either a string or a number
result : ToPrimitive (x) == yie '0' == 0, therefore true

  1. Comparison 0 == [[0]] - operand types differ

Corresponds to case 8 of algo . If Type (x) is either a string or a number and type (y) is Object, the result is : x == ToPrimitive (y). ie 0 == '0', therefore true

  1. Comparison [0] == [[0]] - Types of operands are the same objects ie

Corresponds to case 1 of algo : Type (x) matches type (y), if type is 'object' Returns true if x and y refer to the same object. Otherwise, return false. ie the link will be mapped, therefore false

+1
source

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


All Articles