JavaScript Closures

 

Closure is one of the important concept of Javascript. A closure is a function which has access to all variables from the other function. In other words, a closure is child functions which have access to all variables of their parent function. This is been done by creating a function inside the other function and most importantly they outer/ parent function is not able to access to the scope of inner/child function.

In Javascript, the variable scope is either local or global.

Local Variable: variables declared inside the function, function can full access to it. That is a local variable.

e.g.     

<!DOCTYPE html>

<html>

<body>

<p id="demo"></p>

<script>

 

function add() {

            let a=2;

            document.getElementById("demo").innerHTML=a*a;

}

add();

</script>

</body>

</html>

Output: 4

Global Variable:A function can access the variable defined outside the function. That is a global variable.

e.g.

<!DOCTYPE html>

<html>

<body>

<p id="demo"></p>

<script>

let a=2;

function add() {

            document.getElementById("demo").innerHTML=a*a;

            }

add();

</script>

</body>

</html>

Output: 4

Note: A change is that the “a” variable is defined outside the function it becomes global.

 

Javascript Closure:

Just like the nested function.

1.      Child function can access to parent function variables.

2.      Parent function cannot access the child function variables.

 

 

e.g. of Javascript Closure:

<!DOCTYPE html>

<html>

<body>

<p id="demo"></p>

<script>

function outer() {

var a=4;

      function inner() {

var b=5;

                  document.getElementById("demo").innerHTML=a*b;

      }

inner(); // called inner function inside outer function

}

outer(); // called outer function

</script>

</body>

</html>

Output: 20

 

Comments

Post a Comment

Popular posts from this blog

Teacher As: Critical Pedagogue

ROLE CONFLICT PROBLEM AMONG WORKING WOMEN

Rights and obligations of Issuer, Participant and Beneficial owner under the Depository Act, 1996