O'Reilly logo

Professional, JavaScript® for Web Developers, Second Edition by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 because ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required