Tuesday, February 27, 2007

Anonymous Function in JavaScript

A function can also be defined inside an expression. This is called a function expression. Typically such a function is anonymous; it does not have to have a name. For example, the function square could have been defined as:

const square = function(number) {return number * number};

This is convenient when passing a function as an argument to another function. The following example shows the map function being defined and then called with an anonymous function as its first parameter:

function map(f,a) {
var result=new Array;
for (var i = 0; i != a.length; i++)
result[i] = f(a[i]);
return result;

The call

map(function(x) {return x * x * x}, [0, 1, 2, 5, 10];

returns [0, 1, 8, 125, 1000].

No comments :