What is Javascript closure: Learn Javascript closure in deeply

What is Javascript closure?

What is javascript closure

What is Javascript closure: We can create a closure by adding a function inside another function. Actually javascript is a functional language having both local and global variables.

By default, the global variables are available for access and manipulate all functions. However, the global variables can be made local with the help of closures.

Actually, closure is a function that can be passed around and it holds the same “environment” as the one it had when it was initialized.

Before understanding the closure concept, first, we have to understand the lexical scoping.

Lexical scoping:

By the position of the variable javaScript can define the scope of a variable in the source code. One thing you have to remember that a nested function can have access to variables declared in its outer scope. This concept is called lexical scoping.

Let’s see javascript closure example blew:

The Fruit() function creates a local variable named message and a function named MyFruit(). The MyFruit() is an inner function that is available only within the body of the Fruit() function.

The MyFruit() function has access to the variables of the outer function, therefore, it can access the message variable of the Fruit() function.

Inside the Fruit() function, we can call the MyFruit() function.

The last line calls the Fruit() function displays the “This is an apple” message with an alert box as we expected.

 

A closure function has three scope chains:

  • A closure function has access to its scope (the variables defined between its curly brackets)
  • A closure function can access to the outer function’s variables
  • A closure function can access to the global variables.

Javascript closure example:

This example can help you to better understand Javascript closures.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Javascript closures</title>
</head>
<body>
   <script>
     function outsideFunct() {
      var nu1 = 50;
      function insideFunct() {
       var nu2 = 10;
       console.log(nu1+nu2);
      }
      return insideFunct;
      }
      var X = outsideFunct();
      X();
  </script>
</body>
</html>

Output

60

When the function outsideFunct()  is called it declares another function called insideFunct() which has access to its local variables as well as the outsideFunct()  function’s variables at the time of declaration.

 

Closures that take arguments

  • The function sumFunc(x), takes a single argument, x, and returns a new function. This returned function- called closure – takes an argument y and returns the sum of x and y.
  • The variable firstNo  initializes a closure with x=5 as the argument. Calling fistNo() with any numeric argument will produce an output that adds ‘5’ to this argument.
  •  After initializes a closure in the variable SecondNo with x=10 as the argument. Calling SecondNo() with any numeric argument will produce an output that adds ‘10’ to this argument.

 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Javascript closures</title>
</head>
<body>
<script>
   function sumFunc(x) {
   function add(y){	    
	return x+y
   }
    return add;
   }
   var firstNo = sumFunc(5);
   var SecondNo = sumFunc(10);
   console.log(firstNo(2)); 
   console.log(SecondNo(2));
 </script>
</body>
</html>

Output:

7
12

Always remember one thing that closures are those functions that are defined within another function.  The above examples allow us to set functions to variables and functions even use functions to generate a different function.

When to use Closure in js?

A closure function is very useful in hiding implementation detail in JS. In other words, it can be more useful for us to create private variables or functions.

How to create private functions & variable in the following example blew:

Javascript closure example:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Javascript closures</title>
</head>
<body>
<script>
   var myCounter = (function() {
   var privateCounter = 0;
   function changeBy(vlu) {
     privateCounter += vlu;
   }
   return {
     increment: function() {
     changeBy(1);
     },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
   }
   };   
   })();
   alert(myCounter.value()); // 0
	myCounter.increment();
	myCounter.increment();
	alert(myCounter.value()); // 2
	myCounter.decrement();
	alert(myCounter.value()); // 1
 </script>
</body>
</html>

Output:

use Closure in js

use Closure in js

Closure in js

 

 

decrement(), increment() and value() function are becomes public function in the above example just because they are included in the return object, whereas changeBy() function becomes private function because it’s not returned and only used internally through increment() and decrement() function.

Use JavaScript closure in a loop:

See the following HTML page.

In the above example, we have three links on the same page. When we click any link then the script needs to show us a message with an alert box to inform us which link we have been clicked now.

If we run this and click any link then we will get the same message that:

Thanks for cliking link 4

which is not what we actually expected from this script.

Output:

closure in a loop

 

Now I will explain why we have the number 4 in the output.

The condition of the loop is  i < NumOfLink i.e., 3 in this case. In the body of the loop, we increment the value of  i by 1 and concatenate the result with a string 'Thanks for cliking link '. Therefore the final value of   i + 1 is reflects in the output.

Actually, we are trying to do, in each iteration we are trying to do in the loop is to copy the value of  i at the time of iteration. But it did not work as expected. The reason behind that the functions assigned to click are closures and each closure created in each loop iteration. There is just one i in the shared scope but all three closures share the same lexical scope of the LinkClicker() function.

Solution of Immediately-invoked function expression:

To solve this issue, we can use an immediately-invoked function expression because immediately-invoked function expression is creates a scope by declaring a function and immediately execute it.

Output:

Immediately-invoked function expression

Immediately-invoked function expression

Immediately-invoked function expression

Now, I think you should have a good understanding of Js closure and you can use javascript closure more effectively.

Close