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

A closure is like keeping a copy of the local variables of a JavaScript function as they were when the closure was created. In web programming, closures are frequently used to eliminate the duplication of effort within a program or to hold values that need to be reused throughout a program so that the program doesn’t need to recalculate the value each time it’s used.

Another use for closures is to create customized versions of functions for specific uses.

In this example, closures are used to create functions with error messages specific to different problems that may occur in the program. All the error messages get created using the same function.

When a function’s purpose is to create other functions, it’s known as a function factory.

 function factory


The key to understanding this example is the factory function.

function createMessageAlert(theMessage){
  return function() {
  alert (theMessage);

To use this function factory, assign its return value to a variable, as in the ­following statement:

var badEmailError = createMessageAlert("Unknown email address!");

The preceding statement creates a closure that can be used elsewhere in the program just by running badEmailError as a function, as in the following event handler:


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: