Home

How to Use Closures in Your JavaScript Code

|
Updated:  
2016-03-26 7:38:35
|
JavaScript Essentials For Dummies
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.

<html>
<head>
 <title>function factory</title>
 <script>
 function createMessageAlert(theMessage){
  return function() {
  alert (theMessage);
  }
 }
 
 var badEmailError = createMessageAlert(“Unknown email address!”);
 var wrongPasswordError = createMessageAlert(“That’s not your password!”);
 
 window.addEventListener(‘load’, loader, false);
 function loader(){
  document.login.yourEmail.addEventListener(‘change’,<br/>badEmailError);
  document.login.yourPassword.addEventListener(‘change<br/>‘,wrongPasswordError);
 }
 </script>
</head>
<body>
 <form name=“login” id=“loginform”>
 <p>
  <label>Enter Your Email Address:
  <input type=“text” name=“yourEmail”>
  </label>
 </p>
 <p>
  <label>Enter Your Password:
  <input type=“text” name=“yourPassword”>
  </label>
 </p>
 <button>Submit</button>
</body>
</html>

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:

document.login.yourEmail.addEventListener(‘change’,badEmailError);

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.