-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?

TobotRobot
  • 54
  • 4
  • 3
    The arrays are coerced to string values, which essentially means that `.join()` is called and the results are compared. – Pointy Feb 11 '16 at 00: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*? – Frédéric Hamidi Feb 11 '16 at 00:30
  • The comparison operators never return `NaN`, they always return a boolean. `NaN < NaN` returns `false`. – Barmar Feb 11 '16 at 00:41
  • @Pointy if you put that as an answer I will select it. – TobotRobot Feb 11 '16 at 00: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". – Pointy Feb 11 '16 at 00:46
  • I was also trying to find a comprehensible explanation of this in the ECMAScript spec. But it looks like it's buried in the details of `@@toPrimitive`. – Barmar Feb 11 '16 at 00:48
  • A second look at the ECMA script docs does show NaN is not allowed, but undefined is. I guess I misread that documentation and meant undefined. http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 – TobotRobot Feb 11 '16 at 00:49

1 Answers1

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"
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Although it returns `false` when I try it with a `NaN` argument, the spec says it should return `undefined` in this case. – Barmar Feb 11 '16 at 00:49
  • @Barmar: The abstract algorithm returns `undefined`, so that the actual operator can always return `false` (regardless whether it's `<`, `<=`, `>` or `>=` that invokes the algorithm) – Bergi Feb 11 '16 at 00:53