Skip to main content

Closures in JavaScript

 closure is the wrapping up of function and it's surrounding variables with in a function or lexical scope. 

In the other way we can say, we can access the outer function scope from the inner function. 

So we can say, closure are created when functions are created. 


Example of closure: 


function outerMethod() {
     var name = 'Hello World';
     function innerMethod() {
          console.log(name);
     }
     innerMethod();
}
outerMethod();


So output of the above example is: Hello World

Here the name variable is in the scope of outer function and we are accessing from the inner function. This is closure. 


More understand about closure with it's lexical scoping:  

In JavaScript we can return a function within another function. Please check the below example.

function outerMethod() {
     var name = 'Hello World';
     function innerMethod() {
          console.log(name);
     }
     return innerMethod;
}
var result = outerMethod();

console.log(result);


Now guess what will be the output of result ? 

result will return the function, like the below: 

f innerMethod() {
     console.log(name);
}


Now if we call the result function then then what will be the output ?

result();


Here result variable is holding the "innerMethod" function. And within the function we are using "name" variable. But within the scope of function "name" variable does not declared. So as per this scenario console log output will undefined or null. 

But here also the output will be "Hello World", because of the closure. Because closure already bind both the function and variable within the lexical scope.


Comments

Popular posts from this blog

sum(1)(2)(3)(4)..( n)() in JavaScript

  console.log('sum(1)(2)(3)(4)..( n)()'); // Solution 1: let sum = function (a) { return function (b) { if (b) { return sum(a + b); } return a; } } let result = sum(1)(2)(3)(4)(5)(); console.log(result); // 15 // Solution 2: let sum = (a) => (b) => (b) ? sum(a+b) : a; let result = sum(1)(2)(3)(4)(5)(); console.log(result); // 15

Angular Chart Builder

This is my first angular library, named angular-chart-builder . It's a license free npm library. Anyone can install and integrate this library to there own angular project. Now the angular-chart-builder library have two types of charts that is Progress Bar and Pie Chart .   To get the library, please check the below url:    https://www.npmjs.com/package/angular-chart-builder