0

The JavaScript snippet is as follows:

var a = [1, 2, 3],
    b = [1, 2, 3],
    c = [1, 2, 4]
a ==  b
a === b
a >   c
a <   c

As my understanding, because array is object and when you compare two objects using '==' or '===', you actually compare their reference. So a == b and a === b all returns false. Right?

Considering a > c and a < c comparison, I tried in Chrome and a > c returns false, a < c returns true. As I googled, "Arrays are compared lexicographically with > and <". Does that mean 'a > c' logically equals to:

for (var i = 0; i < Math.min(a.length, c.length); i++) {
   if (a[i].toString() <= c[i].toString)   return false;
}
return true;

Am I right? If not, can anyone help explain the mechanism behind it? thanks a lot.

Lisa
  • 150
  • 2
  • 9
  • more like `a.join() > c.join()` - but I guess that's a bit like your code – Jaromanda X Mar 02 '18 at 01:43
  • What is the use case for performing a `>` or `<` comparison on arrays? What is the use case for using a mathematical comparison operator against strings? Just Silly. – Randy Casburn Mar 02 '18 at 01:52

1 Answers1

0

It converts the arrays to strings, then compares them lexicographically. Converting an array to a string returns the result of array.join(','), so

[1, 2, 3] < [1, 2, 4]

is equivalent to

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

For an array of numbers this is effectively the same as your loop. It might not be equivalent for an array of strings.

For more information about how coercion is done in comparison operators see How do the JavaScript relational comparison operators coerce types?

Barmar
  • 741,623
  • 53
  • 500
  • 612