Home > Software engineering >  What does comparing 2 Array mean in Javascript? [duplicate]
What does comparing 2 Array mean in Javascript? [duplicate]

Time:09-24

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!

CodePudding user response:

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.

  • Related