JavaScript closure description

A brief introduction to the subject of closures is the key to understanding how JavaScript functions work

If you ever wroteFeaturesIn JavaScript, you have taken advantage ofClosure.

This is an important topic and has an impact on what you can do.

When a function runs, it will be executedScope at the time of definition, withIs notHas the state when it is in the proper stateBe executed.

The scope is basically the set of visible variables.

A function remember itVocabulary range, And can access variables defined in the parent scope.

In short, a function has all the variables accessible.

Let me immediately give an example to clarify this point.

const bark = dog => {
  const say = `${dog} barked!`
  ;(() => console.log(say))()


This logs to the consoleRoger barked!,as expected.

What if you want to return to the operation:

const prepareBark = dog => {
  const say = `${dog} barked!`
  return () => console.log(say)

const bark = prepareBark(Roger)


This code snippet is also logged to the consoleRoger barked!.

Let's make the last example, which can be reusedprepareBarkTwo different dogs:

const prepareBark = dog => {
  const say = `${dog} barked!`
  return () => {

const rogerBark = prepareBark(Roger) const sydBark = prepareBark(Syd)

rogerBark() sydBark()

This print

Roger barked!
Syd barked!

As you can see, the state of the variable say is linked to the function that’s returned from prepareBark().

Also notice that we redefine a new say variable the second time we call prepareBark(), but that does not affect the state of the first prepareBark() scope.

This is how a closure works: the function that’s returned keeps the original state in its scope.

More js tutorials: