Skip to Main Content
Professional, JavaScript® for Web Developers, Second Edition
book

Professional, JavaScript® for Web Developers, Second Edition

by Nicholas C. Zakas
January 2009
Intermediate to advanced content levelIntermediate to advanced
836 pages
21h 30m
English
Wrox
Content preview from Professional, JavaScript® for Web Developers, Second Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional: JavaScript® for Web Developers, Third Edition

Professional: JavaScript® for Web Developers, Third Edition

Nicholas C. Zakas
JavaScript: Best Practice

JavaScript: Best Practice

James Kolce, Moritz Kroger, Ivan Curic, Samier Saeed, Jeff Mott, M. David Green, Craig Buckler

Publisher Resources

ISBN: 9780470227800Purchase book