Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript named sort function

I was wondering if it's possible to pass a named function to Array.sort(). I'm trying to do something like the logic below but obviously it complains about a not being defined.

if (iWantToSortAscending) {
    myArray.sort(sortAscending(a, b));
} else {
    myArray.sort(sortDescending(a, b));
}

// my lovely sort functions
function sortAscending(a, b) {
    ...
    sorty worty
    ...
}

function sortDescending(a, b) {
    ...
    sorty worty differently
    ...
}

Obviously I could get the code to work like below, and it does, but I'd rather not be using anonymous functions for the sake of readability and debugging.

if (iWantToSortAscending) {
    myArray.sort(function (a, b) {
        ...
        sorty worty
        ....
    }
} else {
    ...
like image 977
Thomas Mitchell Avatar asked Dec 24 '22 23:12

Thomas Mitchell


2 Answers

Think "what is my program doing?"

myArray.sort(sortAscending(a, b));

What does it do? It tries to call myArray.sort with result of expression sortAscending(a,b). First of all, a and b aren't defined, so it throws (ReferenceError). But what if a and b are defined? Result of expression sortAscending(a,b) wouldn't be a function.

To get things working, you have to use code myArray.sort(sortAscending); - it passes a function as argument.

like image 30
Ginden Avatar answered Dec 27 '22 14:12

Ginden


It sure is, but you have to reference the function, not call it, and arguments are passed automagically

myArray.sort(sortAscending);

whenever you add parentheses and arguments to a function, it's called immediately.
When you want it to be called by another function, for instance as a callback in sort(), you reference it, and leave the parentheses out.

like image 116
adeneo Avatar answered Dec 27 '22 12:12

adeneo