Search code examples
javascriptarrayscmp

How are Javascript array compared?


Is there a standard defined how would JavaScript be compared, on Chrome console I get this

[10,0,0] > [1,0,0]
true
[10,0,0] > [5,0,0]
false
[5, 0, 0, 0] < [10, 0, 0, 0] //repeatable
false

[10,0,0,0] > [9,0,0,0]
false
[11,0,0,0] > [10,0,0,0]
true

Which is highly unintutive, and I can't even make sense what logic is being applied, and they look repeatable so doesn't look based on object id(ref) etc, so is there any documentation for it?


Solution

  • JavaScript arrays are converted to strings and the strings are then compared. So.

    [10,0,0].toString() => "10,0,0"
    [5,0,0].toString() => "5,0,0"
    

    Strings are compared lexicographically, so "5,0,0" is bigger than "10,0,0".