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){ ...

Get Learning AngularJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.