Why or how does this prove JavaScript array equality?

arrays, equality, javascript

Solution

With `<`/`>`, the arrays are converted to strings first, and as such do not provide a reliable method of checking equality.

`==` does not work because objects are checked by reference:

[] == []; // false, two separate objects

var a = [];
a == a; // true, refer to the same object

The `<`/`>` trick is flawed:

var a = [1, [2, 3]],
    b = [[1, 2], 3];

!(a<b || b<a); // true

This evaluates to `true`, because they are both converted to the string `"1,2,3"` before they are checked (`<`/`>` do not "directly" work for objects).

So basically, you are comparing equality of the strings. For strings, `a == b` is indeed the same as `!(a<b || b<a)` - `<`/`>` for strings check character codes, so two equal strings are neither "smaller" nor "greater" because that's not the case for any character code in the strings.

Problem

In this answer there is a simple function that will return array equality for arrays that contain primitive values. However, I'm not sure why it works. Here is the function: ``` function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); } ``` I'm mostly interested in the second half; this bit: ``` !(a<b || b<a) ``` Why does the `<` and `>` work when comparing the arrays but the `==` doesn't? How do the less than and greater than methods work within JavaScript?

Original source

Related problems