Closure

The best thing that JavaScript ever got was closures. A function in JavaScript has access to any variables defined in the outer scope. Closures are best explained with examples:

  1. function outerFunction(arg) {
  2. var variableInOuterFunction = arg;
  3. function bar() {
  4. console.log(variableInOuterFunction); // Access a variable from the outer scope
  5. }
  6. // Call the local function to demonstrate that it has access to arg
  7. bar();
  8. }
  9. outerFunction("hello closure"); // logs hello closure!

You can see that the inner function has access to a variable (variableInOuterFunction) from the outer scope. The variables in the outer function have been closed by (or bound in) the inner function. Hence the term closure. The concept in itself is simple enough and pretty intuitive.

Now the awesome part: The inner function can access the variables from the outer scope even after the outer function has returned. This is because the variables are still bound in the inner function and not dependent on the outer function. Again let’s look at an example:

  1. function outerFunction(arg) {
  2. var variableInOuterFunction = arg;
  3. return function() {
  4. console.log(variableInOuterFunction);
  5. }
  6. }
  7. var innerFunction = outerFunction("hello closure!");
  8. // Note the outerFunction has returned
  9. innerFunction(); // logs hello closure!

Reason why it’s awesome

It allows you to compose objects easily e.g. the revealing module pattern:

  1. function createCounter() {
  2. let val = 0;
  3. return {
  4. increment() { val++ },
  5. getVal() { return val }
  6. }
  7. }
  8. let counter = createCounter();
  9. counter.increment();
  10. console.log(counter.getVal()); // 1
  11. counter.increment();
  12. console.log(counter.getVal()); // 2

At a high level it is also what makes something like Node.js possible (don’t worry if it doesn’t click in your brain right now. It will eventually ?):

  1. // Pseudo code to explain the concept
  2. server.on(function handler(req, res) {
  3. loadData(req.id).then(function(data) {
  4. // the `res` has been closed over and is available
  5. res.send(data);
  6. })
  7. });