JavaScript Closures explained

If you’ve ever written a Function JavaScript allows you to already make use of Closings.

This is an important topic that you should understand. It has implications for what you can do.

Execution occurs when a function has been run.With the scope in place at the time it was defined?, and Not With the state that is in place when it is Executed.

The scope simply refers to the number of variables visible.

A function retains its Lexical Scope and is able access variables that are defined in the parent scope.

In other words, a function can access all the variables in its baggage.

To clarify, let me give you an example.

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

bark(`Roger`)

 Roger barked!, , and this logs to his console.

What if the goal is to reverse the action?

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

const bark = prepareBark(`Roger`)

bark()

This snippet logs to  Roger barked!. console!

Let’s look at one more example. prepareBark can be reused for two different breeds of dogs.

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

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

rogerBark()
sydBark()

This prints

Roger barked!
Syd barked!

As you can clearly see, the Please state The variable  say  is tied to  prepareBark().

You will also notice that  prepareBark() defines a new say variable twice, but this does not alter the state for the first  prepareBark()scope.

This is how closure works: the function returned maintains its original scope.