Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

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.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: