JavaScript tip 2: Function factories using closures

Here’s how we can use closures to build “function factories”:

var addElement = function(destination) {
  return function(element) {
    document.getElementById(destination)
            .appendChild(element);
  }
};

var addElementToMain = addElement("main");
var addElementToAlternate = addElement("alternate");

var p = document.createElement("p");
p.appendChild(document.createTextNode("Vanilla JS"));

addElementToMain(p);

You can also check out and run this example as a CodePen here.

In this example, addElement is a function which will return a new function with the destination parameter closed. This way we can create functions to add child elements to various parent elements.

The addElementToMain and addElementToAlternate are two functions created this way.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s