How to legitimately use a function name as an argument for another function in JavaScript?

I prepared for Javascript, read tutorials on W3Schools and came across this code:

function sortNumber(a, b)
{
return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));

It sorts the elements in an array, quite simply. But how can we pass sortNumber(function name) as a parameter to the sort function?

Source example

+3
source share
7 answers

Surprisingly, JavaScript has its roots in the Scheme language.

The scheme allows some functions (called "lambda functions") to move as if they were a variable.

JavaScript , . ( , " JavaScript".)

, :

// Assign a function to foo
var foo = function () { alert('bar'); };

// Call foo like a function
foo();

"bar".

lambdas "Adder":

adder = function (x) {
    return function (y) {
        x + y
    }
};
add5 = adder(5);
add5(1); // == 6

, .

+3

But how can we pass sortNumber ( a function name) as a parameter to the sort function?

JS . , ?

+4

sort Javascript, , , , .

, , , .

+2

, . , : "sortNumber".

sort() ( ) , .

+1

- javascript.

, , -1, 0 1 ( , b)

a-b , , .

+1

W3Schools: http://www.w3schools.com/jsref/jsref_sort.asp

the sort () method of the array takes one parameter, which is the function handler.

0
source

A variable in javascript can contain any type of value that includes functions. If you use a function name without parentheses, refer to this function and do not call it at all.

0
source

Source: https://habr.com/ru/post/1731037/


All Articles