Closures

A brief example of what they are and how they work.

A closure is an inner function that has access to the variables and parameters of its outer function.

Let’s look at the following example to understand how it works:

function retirement(retirementAge){
  var a = ' years left until retirement.';
  return function(yearOfBirth){
console.log((retirementAge - age) + a);
}
}
var retirementUS = retirement(66);
retirementUS(1990); // 40 years left until retirement.
retirement(66)(1990); // 40 years left until retirement.

The closure in this example is the anonymous function (inside the retirement function) that accepts yearOfBirth as its argument.

We can call the outer retirement function in two ways:

1) var retirementUS = retirement(66);
retirementUS(1990); //40 years left until retirement.
2) retirement(66)(1990); //40 years left until retirement.

As shown above, passing in the inputs 66 and 1990 gives us the output: 40 years left until retirement. This is the result of retirementAge - age (40) + a ( ‘ years left until retirement’).

You can see that variable a is accessed by the closure to output the string “years left until retirement.” This access is possible, because a is within the scope of the retirement function and, per our definition, a closure has access to variables within its outer function. Thus, it can still access variable a, even after the retirement function has finished executing.

The bottom line about closures is that it has access to three scope chains: 1) it’s own scope (i.e., everything within the function that accepts yearOfBirth), 2) the outer function’s scope (i.e., everything within the retirement function), and 3) the global scope (i.e., everything outside of the retirement function).

Hopefully this helped you clarify certain concepts about closures!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.