Using Anonymous Functions

So far, all the examples you have seen show named functions. JavaScript also lets you create anonymous functions. These functions have the advantage of being defined directly in the parameter sets when you call other functions. Thus you do not need formal definitions.

For example, the following code defines a function doCalc() that accepts three parameters. The first two should be numbers, and the third is a function that will be called and passed the two numbers as arguments:

function doCalc(num1, num2, calcFunction){
    return calcFunction(num1, num2);
}

You could define a function and then pass the function name without parameters to doCalc(), as in this example:

function addFunc(n1, n2){
    return n1 + n2;
}
doCalc(5, 10, addFunc);

However, you also have the option to use an anonymous function directly in the call to doCalc(), as shown in these two statements:

console.log( doCalc(5, 10, function(n1, n2){ return n1 + n2; }) );
console.log( doCalc(5, 10, function(n1, n2){ return n1 * n2; }) );

You can probably see that the advantage of using anonymous functions is that you do not need a formal definition that will not be used anywhere else in your code. Anonymous functions, therefore, make JavaScript code more concise and readable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.234.24