I was gearing up for Javascript, reading the tutorials at 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 the Array, pretty simple. But how can we pass sortNumber ( a function name) as a parameter to the sort function?
Surprisingly, JavaScript has its roots in a language called Scheme.
Scheme allows certain functions (called ‘lambda functions’) to be passed around as though they were a variable.
JavaScript handles functions in much the same way scheme did. (Some people say that “functions are first-class-citizens in JavaScript.”)
For example, you can write:
The result would be that the message ‘bar’ is shown.
The classic example of lambdas is the “Adder” example:
Hope this helps.