Chapter 7. Anonymous Functions

An anonymous function is any function that doesn't have a name; these are also sometimes referred to as lambda functions. Anonymous functions are incredibly powerful programming tools and can be used in any number of ways. Consider the following typical function declaration:

function functionName(arg0, arg1, arg2) {
    //function body
}

As discussed earlier in the book, functions can be declared in this manner or defined as a function expression such as the following:

var functionName = function(arg0, arg1, arg2) {
    //function body
};

Even though this example is logically equivalent to the previous one, there are some slight differences. The primary difference between function declarations and function expressions, of course, is that the former are loaded into the scope before code execution whereas the latter are unavailable until that particular line has been evaluated during code execution (discussed in Chapter 5). Another important distinction is that function declarations assign a name to the function, whereas function expressions actually create anonymous functions and assign them to a variable. This means the second example creates an anonymous function with three arguments and assigns it to the variable functionName, but the function itself doesn't have a name assigned.

It's also possible to write an anonymous function like this:

function (arg0, arg1, arg2){
    //function body
}

This code is completely valid. Of course, the function can never be called ...

Get Professional, JavaScript® for Web Developers, Second Edition 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.