-1

Inside my node.js REPL I create 4 arrays : a = [1,2,3], b=[], c=[4,5], d=null ( ok d is not an array but you get my point)

I compare them directly this way :

> b = []
[]
> a > b
true
> b > a
false
> a > c
false
> c > a 
true
> c > b
true
> b > c
false
> d > a
false
> a > d
false

What are these expressions actually evaluating? I see that it's clearly not the length of the arrays. Otherwise c > a would have been false.

Can somebody please help me understand!

Rohit Rane
  • 2,790
  • 6
  • 25
  • 41
  • 1
    You need to learn a lot of javascript's implicit conversions (i personally prefer explicit ones, where comparing arrays like that just throws, but it is what it is), and use them one after another. – ASDFGerte Sep 23 '21 at 18:40
  • 1
    The short version is, JavaScript is casting the array to some other type and using that type's comparator for the `operator>` evaluation. Since these results don't have any valuable semantic meaning, it's basically a pointless operation and you should create your own routine for comparing arrays if you need that functionality. There isn't much point in further stressing *why* JavaScript chooses to implement things this way, as there are many other examples of weird JavaScript behavior. – h0r53 Sep 23 '21 at 18:49

1 Answers1

0

The arrays get converted to strings first (including the commas).

[1, 2, -3] for instance becomes the string '1,2,-3'

Then the strings get compared in an "alphabetical" order (based on their character codes).

It is not a very intuitive way of accomplishing comparisons, and should be avoided.

maybebot
  • 137
  • 1
  • 5