-1

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?

7
  • 3
    The arrays are coerced to string values, which essentially means that .join() is called and the results are compared. Commented Feb 11, 2016 at 0:28
  • 2
    You were expecting NaN as the result of the less-than operator? So you do think things like 42 is NaN than 666? Commented Feb 11, 2016 at 0:30
  • The comparison operators never return NaN, they always return a boolean. NaN < NaN returns false. Commented Feb 11, 2016 at 0:41
  • @Pointy if you put that as an answer I will select it. Commented Feb 11, 2016 at 0:45
  • @TobotRobot thanks - I've been looking for a duplicate, but I can't find a good one. We really need a comprehensive, understandable uber-question for "Mysteries of JavaScript relational operators". Commented Feb 11, 2016 at 0:46

1 Answer 1

0

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Although it returns false when I try it with a NaN argument, the spec says it should return undefined in this case.
@Barmar: The abstract algorithm returns undefined, so that the actual operator can always return false (regardless whether it's <, <=, > or >= that invokes the algorithm)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.