Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 22, 2021 12:09 pm GMT

An Intro To Closure In JavaScript

Introduction:

In this article, I am going to walk you through the basics of closure in JavaScript, as simply as I can.

Prerequisite:

If you have a prior knowledge of lexical scope in JavaScript and for some reason, you have not yet grasped the concept of closure, then this article is for you.

Why You Should Understand Closure:

  1. Closure is all around us.
  2. Closure forms the foundation for separating large codes into separate, yet interdependent modules.
  3. Chances are that you're already using closure in your code without even knowing it.

At the end of this article, you should:

  1. have a good grasp of the basics.
  2. be able to recognize closures in your code. As I pointed out earlier, you're probably using it already, without knowing.

Let's dive in.

What Is Closure?

Closure is when a function can still remember and access its lexical scope even when that function is executed outside its lexical scope. Lexical scope means: the scope where the function was defined.

Illustration:

function hour(){    var hr = 2;    function min(){        console.log(hr);    }    return min;}var time = hour();time();       //output:   2

Let's walk through the above code snippet.

  1. First, we define a function hour. This function creates a scope which wraps (or hides) everything in it from the outside world.
  2. Next, within hour, we declare a variable hr and assign it a value of 2.
  3. Still within hour, we define another function min which creates its own scope within the scope of hour. Notice that min references the variable hr in its definition.
  4. Finally within hour, we return out min.
  5. Moving outside the scope of hour, hour is executed (or called). The result of this call (min) is assigned to a new variable time.
  6. We then execute time, which of course executes our returned function min. So min is executed outside the scope we declared it in.

We get an output of 2 which is the value of hr. This is shocking!

We expect function hour(and everything in it, including hr) to be garbage-collected immediately we exit the function(at the return statement). So how come min can still access the variable hr and the entire scope of the hour function? This is closure at work.

Closure lets min to continue to have access to the scope it was defined in, which is hour in our case. We can say that closure kept the scope of hour alive for min to access at anytime (and at any location) within the program.

The Famous setTimeout Function:

Using the famous setTimeout function is one of many ways we use closure in our everyday code.

function delay(){    var response = "Ok";    setTimeout(function timeCount(){        console.log(response);    }, 2000);}delay();
  1. First we author a lexical scope by defining a function delay.
  2. Next, within delay, we declare a variable response and assign the string "Ok" to it.
  3. Next, we create a function called timeCount and pass it to setTimeout as a first argument, alongside 2000 as the second argument.
  4. Finally we execute delay.
  5. Be aware that timeCount has a closure over the scope of delay. Hence when timeCount is executed within setTimeout 2000 milliseconds later, it still has access to the scope of delay, even when delay's scope should have died off already. This is closure at work again.

Conclusion:

In the last few minutes (or seconds, Lol), We have learned the basic concept of closure, and seen how it is used in code, and in the setTimeout function.

In the next article, we will take a deeper dive into closure - how it works hand in hand with loops, and how it forms the foundation for module patterns. We will also look at the concept of PLSRD (Persistent Lexically Scoped Referenced Data).

Till next time folks


Original Link: https://dev.to/barnabas19/an-intro-to-closure-in-javascript-397l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To