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 {
...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With