JavaScript closures explained

During my online learning endeavors, I have continually come across the word “closure”. I didn’t really know what it was, but like any inquisitive mind that loves to learn, there is never a time like the present to figure out what JavaScript Closures are.

MDN documentation on JavaScript Closures:

First thing to do is to check out the MDN documentation and they have a good description:

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure ‘remembers’ the environment in which it was created.

Check out these JavaScript closures examples

Consider the following HTML and JavaScript:

<!DOCTYPE html>
  <title>THIS IS A PAGE</title>
  <p>an html page</p>
    function makeColor(theColor) {
      var toChangeTo = theColor;
      return function() { = toChangeTo;

If I open this page, it is blank and looks as follows:

original page without execution of javascript closures

Now, if in the console, I create a variable:

var theThings = makeColor("red");

Notice the actual function is returned. Since functions in JavaScript are first class citizens, they can be passed around similar to variables. This really is one of the beautiful and dangerous things about JavaScript.

So the variable is a function that was returned from makeColor, but when I do the following:

final - after execution of javascript closures

I call “theThings()”, and not only does it execute the returned function, but it remembers and is aware of the variable toChangeTo. That is what makes this a closure. theThings remembers the environment in which it was created and that toChangeTo was “red”, so it was able to change colors when executed.

Closures are not just a JavaScript tool and are available in some other languages, but JavaScript it is where I am exposed to them most often. JavaScript’s treatment of functions as first class citizens is one of the great things about the language and also creates opportunities to utilize closures. If you had confusion about what a closure is, I hope this helps get you closer and you may begin to notice just how often it is used.

Leave a Reply

Your email address will not be published. Required fields are marked *