Search code examples
javascriptarrayscomparison-operators

What do comparison operators compare on arrays in javascript?


I was surprised to find the comparison of two arrays to return a boolean in JavaScript.

var blah = [1,2,3];
var blah2 = [2,3,4,5];

document.write(blah < blah2);

I was honestly expecting NaN, but in every browser I tested I got a consistent "true" result. I couldn't find any documentation on what comparison operators do with arrays in JS. What is being compared in this case?


Solution

  • I was honestly expecting NaN

    No. A comparison always returns a boolean in javascript (when it doesn't throw an exception).
    If any of the operands is not comparable (like NaN), it would return false.

    What is being compared in this case?

    The abstract relation comparison algorithm converts all arguments to primitive values to compare them. In the case of your arrays, this will cast them to strings, so you're essentially comparing

    "1,2,3" < "2,3,4,5"