How do closures work in JavaScript?



In this article, we are going to learn about ‘closure’ and how they actually work in JavaScript. The closure is basically a combination of a function that is enclosed with the references to its surrounding state (Also known as the lexical environment).

In JavaScript, closures are basically created every time a function is created at run time. In other words, a closure is just a fancy name that remembers the external things used inside it.

Let’s understand the JavaScript closures with the help of some examples −

Example 1

In the example below, we will be declaring a closure that would eventually be able to access an outer variable tagLine from the outer function

After using the outer variable in the innermost function, this particular closure will help the user to alert tagLine every time the outer function is called.

#Filename: index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      Closures in Javascript
   </title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <button type="button" onclick="init()">
      Click here!!!
   </button>
   <p id="demo"></p>
<script>
   function init() {
      var tagLine = "Start your Learning journey now";
      function display() { // display() is the inner function, a closure
         alert(tagLine); // use variable declared in the parent function
      }
      display();
   }
   </script>
</body>
</html>

Output

This will produce the following result.

Example 2

In the below example, we are using the nested closures to call two functions and display the output of the same function.

#Filename: index.html

<!DOCTYPE html>
<html>
<head>
   <title>
      Closures in Javascript
   </title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <button type="button" onclick=" Counter()">
      Click Me!
   </button>
   <p id="demo1"></p>
   <p id="demo2"></p>
<script>
function Counter() {
   var counter = 0;
   function outerfunction() {
   counter += 1;
   document.getElementById("demo1").innerHTML
      = "Outer Counter called = " + counter +" from Outer Function " ;
      function innerfunction() {
         counter += 1;
         document.getElementById("demo2").innerHTML
         = "Inner Counter called = " + counter +" from Inner Function ";
      };
      innerfunction();
   };
   outerfunction();
};
</script>
</body>
</html>

Output


Advertisements