0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Closures

Last updated at Posted at 2019-12-13

#What is a closure?#

function retirement(retirementAge) {
  var a = " years left until retirement";
  return function(yearOfBirth) {
    var age = 2019 - yearOfBirth;
    console.log(retirementAge - age + a);
  };
}

var retirementUS = retirement(66);
retirementUS(1970);
retirement(66)(1970);

In the example code above, the outer function is still able to access variables and arguments from the outside function (scope) even when the outside function has stopped its execution (returned).

An inner function has always access to the variables and parameters of its outer function, even after the outer function has returned.

Closures are used for data privacy.

Why does it work?##

Even if the function execution is removed from the execution stack, the function scoope still remains in the scope chain. The variable object of the outer function remains within

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?