A Quick Look at Closure in JavaScript - thinklab - thinklab

A Quick Look at Closure in JavaScript

If you write any amount of JavaScript, then you’ll no doubt already be using closure in your code; perhaps without even realising it…

What is Closure?

A closure in JavaScript, is simply an inner function that has access to an outer function’s variables via the scope chain. Take the basic example below:

function outer(passedValue) {
  
  function inner(innerValue) {
    return passedValue + innerValue;
  }

  return inner;

}

The inner function has access to the passedValue variable that is passed into the outer function. The JavaScript engine had to look outside of the inner function’s lexical environment to find passedValue, which it found within the containing function’s scope. Using this same premise, the inner function would also have access to variables stored in the global scope.

That’s closure in a nutshell, however, there are several things to consider when using closure in JavaScript.

References only please

Closures store references of variables, rather than copies of them. Consider the example below:

function myFunc() {
  var myVar = 10; // inner functions get access to this variable

  return {

    returnMyVar: function() {

      return myVar; // returns variable

    },

    returnMyNewVar: function(newVar) { // excepts new value as argument

      myVar = newVar; // updates myVar variable with new value

    }

  }
}

var getMyVar = myFunc(); // return outer function

getMyVar.returnMyNewVar(12); // update myVar variable

getMyVar.returnMyVar(); // function updates outer variables value (12)

getMyVar.returnMyNewVar(13); // update myVar variable a second time

getMyVar.returnMyVar(); // function updates outer variables value again (13)

In the example above, we can see how the inner functions returnMyVar and returnMyNewVar are able to make reference to the myVar variable – even after the outer function has been returned. Each time this variable is changed, the inner functions get access to the updated reference of it, rather than a copy of it stored in memory.

That’s a bit IIFE

One issue with closures having access to updated variable references, is when your code relies on closure within a loop. You can get around this by using an Immediately Invoked Function Expression or IIFE, as shown below:

function myOuterFunction() {

  var arr = []; // setup empty array

    for(var i = 0; i < 3; i++) { // initiate for loop to check that the value of i meets specified conditions
      arr.push( // push each value into our array
        (function(val) { // inner function wrapped inside parens (IIFE)
          return function() {
            console.log(val); // inner function logs value for i to the console
          }
        }(i)) // inner function is immediately invoked by passing i as the parameter
      )
    }

  return arr;
}

var checkValue = myOuterFunction(); // return outer function

checkValue[0](); // 0
checkValue[1](); // 1
checkValue[2](); // 2

In the example above, the inner anonymous function was immediately invoked to ensure that it logged a value for i, each time a value was passed into it. Had we not have used an immediately invoked inner function, myOuterFunction would have finished running the for loop and created a reference for i (3), before our inner function was run. Each checkValue call would then have logged 3 instead of 0, 1, and 2 respectively.

Closure FTW

There are many more examples of closure in JavaScript than we’ve covered here, but hopefully this has given you a brief insight into closure and helped you to understand a bit more about how closure works. If you’re keen to learn more, I recommend checking out the following links:

Happy coding!

Brought to you by Christian Redecen-Davies

Designer. Traveller. Photographer. Purveyor of fine pixels since 1999.

See all posts by Christian Redecen-Davies

Comments