5

I want to sort an array containing undefined/null and numbers, so that undefined/null values always come first:

function sorter(a, b) {
    if (a == b) return 0;
    if (a == undefined) return -1;
    if (b == undefined) return  1;
    return a - b;
}

However, when the array contains an undefined value it becomes the last element

[-1, 0, 1, undefined, 2, 3].sort(sorter);     // [-1, 0, 1, 2, 3, undefined]

while it gets sorted correctly if the value is null

[-1, 0, 1, null, 2, 3].sort(sorter);          // [null, -1, 0, 1, 2, 3]

What am I doing wrong? Shouldn't this result in exactly the same order since null == undefined?

Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44
  • They are not the same... The answer from mar10 clears it - http://stackoverflow.com/questions/2559318/how-to-check-for-an-undefined-or-null-variable-in-javascript – RicardoVallejo Jun 08 '16 at 20:27

1 Answers1

1

If you add console.log(a, b) to your sorter function, you'll see that the undefined value is never passed into the sorter function. I think that the interpreter thinks the it's a "gap" in the array and thus don't really consider it as a value.

And by the way, null == undefined is true, but null === undefined is false, they are not the same thing.

Gilad Artzi
  • 3,034
  • 1
  • 15
  • 23