How to Use Anonymous Functions to Code with JavaScript - dummies

How to Use Anonymous Functions to Code with JavaScript

By Chris Minnick, Eva Holland

The function name part of the function head isn’t required in JavaScript, and you can create functions without names. This may seem like an odd thing to do because a function with no name is like a dog with no name; you have no way to call it! However, anonymous functions can be assigned to variables when they are created, which gives you the same capabilities as using a name within the function head:

var doTheThing = function(thingToDo) {
 document.write(“I will do this thing: “ + thingToDo);
}

Knowing the differences between anonymous and named functions

There are a couple important, and sometimes useful, differences between creating a named function and assigning an anonymous function to a variable. The first is that an anonymous function assigned to a variable only exists and can only be called after the program executes the assignment. Named functions can be accessed anywhere in a program.

The second difference between named functions and anonymous functions assigned to variables is that you can change the value of a variable and assign a different function to it at any point. That makes anonymous functions assigned to variables more flexible than named functions.

Self-executing anonymous functions

Another use for anonymous functions is as self-executing functions. A self­executing anonymous function is a function that executes as soon as it’s created.

To turn a normal anonymous function into a self-executing function, you simply wrap the anonymous function in parentheses and add a set of parentheses and a semicolon after it.

The benefit of using self-executing anonymous functions is that the variables you create inside of them are destroyed when the function exits. In this way, you can avoid conflicts between variable names, and you avoid holding variables in memory after they’re no longer needed. This example demonstrates how to write and use self-executing anonymous functions.

var myVariable = “I live outside the function.”;
(function() {
 var myVariable = “I live in this anonymous function”;
 document.write(myVariable);
})();
document.write(myVariable);

Web application programmers use anonymous functions regularly to accomplish a wide variety of modern effects in web pages.