Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do return -1, 1, and 0 mean in this Javascript code?

Tags:

javascript

Here is the context:

function compare (value1, value2) {
    if(value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}

var values = [0, 6, 8, 5];
values.sort(compare);
alert(values); // 0,5,6,8

does -1 return the last argument? Like when using -1 in an array?

like image 613
Briefbreaddd Avatar asked Nov 27 '11 00:11

Briefbreaddd


1 Answers

No, -1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second, 1 means it goes after, and 0 means they're equivalent.

The sort function uses the comparisons in the function you pass it to sort the function. For instance, if you wanted to sort in reverse order, you could make line 3 return 1; and line 5 return -1.

like image 170
Hal Avatar answered Oct 17 '22 06:10

Hal