Power of javascript closure

Closure

It is a advance concept of javascript. This is really interesting concept in javascript. So basically it is a function inside function which can access outer function properties. According to MDN
“A closure is the combination of a function and the lexical environment within which that function was declared.”

So to understand this you need to understand Function, Arguments, Scope. Now we need to understand with basic example –

Also read :-Function, Arguments

Closures

Basic reprasentation

Basic use of Closure

Example 1


function outer(msg) {
  return function inner() {
    return msg;
  }
}

var o = outer("I am outer scope msg");
o(); // I am outer scope msg

Example 2


var add = (function () {
    var count = 0;
    return function () {return count += 1;}
})();

add(); // 1
add(); // 2

So now you can see The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

Private methods with closures

Example 3


var Cls = (function() {

 var mymsg = "Welcome into closures"; 

 function msg() {
   return mymsg;
 }

 return {
   msg: msg
 }
}());

Cls.msg(); // Welcome into closures

Here you can see Cls is outer function that is returning object which is accessing private function inside Cls function and msg function also using mymsg private variable. So when we calling msg function then we are getting mymsg msg in return of function.

Sum with closures

Example 4


function sum(a) {

  return function(b) {
    return a + b; // takes "a" from the outer lexical environment
  };
}

console.log(sum(1)(2)) //3

Here you can see sum is outer function and in first case you are passing 1 then you will get return inner function. Now again you are passing parameter 2 so yo are calling return function and here previous parameter and current parameter doing addition operation and at last you will get return desire output.

You May Also Like

About the Author: admin