Can someone please describe the outcome of these expressions?
[1, 2, 4] < [1, 2, 5] // true
[1, 3, 4] < [1, 2, 5] // false
[1, 2, 3] === [1, 2, 3] // false
[1, 2, 3] < [1, 2, 3] // false
[1, 2, 3] == [1, 2, 3] // false
[1, 2, 3] > [1, 2, 3] // false
[1, 2, 3] <= [1, 2, 3] // true
[1, 2, 3] >= [1, 2, 3] // true
Thanks for help and fast answer !
[1, 2, 3] == [1, 2, 3]
is described under The Abstract Equality Comparison Algorithm, which basically says
(if x or y are primitives, compare them, otherwise...)
Return true if x and y refer to the same object. Otherwise, return false.
Since different object literals always represent different objects, even if the content is the same, the above comparison fails.
Relative comparisons are different from equality. When you use < or >, arrays are compared as strings.
[1, 2, 4] < [1, 2, 5]
The Abstract Relational Comparison Algorithm converts both operands to primitives. If an operand is an object, ToPrimitive calls [[DefaultValue]] which in turn is the same as obj.valueOf().toString(). Since valueOf of an object is the object itself, the whole thing boils down to
"1,2,4" < "1,2,5"
A common assumption that arrays are compared element-wise is not true:
[10,1,3] < [101,5] // false
Note that valueOf can be overridden to affect the behavior of relational operators:
> a = [1,2,3]
[1, 2, 3]
> a < [1,2,4]
true
> a.valueOf = function() { return 'zzz' }
function () { return 'zzz' }
> a < [1,2,4]
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With