1.

What Is A “closure” In Javascript? Provide An Example

Answer»

A closure is a function defined inside another function (called the parent function), and has access to variables that are DECLARED and defined in the parent function scope.

The closure has access to variables in three scopes:

  • Variables declared in their own scope
  • Variables declared in a parent function scope
  • Variables declared in the global namespace

var globalVar = "ABC";
// Parent self invoking function 
(function outerFunction (outerArg) { // BEGIN of scope outerFunction
// Variable declared in outerFunction function scope 
var outerFuncVar = 'x';
// Closure self-invoking function 
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y"; 
console.log(
"outerArg = " + outerArg + "N" +
"outerFuncVar = " + outerFuncVar + "n" +
"innerArg = " + innerArg + "n" +
"innerFuncVar = " + innerFuncVar + "n" +
"globalVar = " + globalVar);
}// end of scope innerFunction)(5); // Pass 5 as parameter 
}// end of scope outerFunction )(7); // Pass 7 as parameter 

innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.

THUS, the output of the code above would be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc

A closure is a function defined inside another function (called the parent function), and has access to variables that are declared and defined in the parent function scope.

The closure has access to variables in three scopes:

var globalVar = "abc";
// Parent self invoking function 
(function outerFunction (outerArg) { // begin of scope outerFunction
// Variable declared in outerFunction function scope 
var outerFuncVar = 'x';
// Closure self-invoking function 
(function innerFunction (innerArg) { // begin of scope innerFunction
// variable declared in innerFunction function scope
var innerFuncVar = "y"; 
console.log(
"outerArg = " + outerArg + "n" +
"outerFuncVar = " + outerFuncVar + "n" +
"innerArg = " + innerArg + "n" +
"innerFuncVar = " + innerFuncVar + "n" +
"globalVar = " + globalVar);
}// end of scope innerFunction)(5); // Pass 5 as parameter 
}// end of scope outerFunction )(7); // Pass 7 as parameter 

innerFunction is closure that is defined inside outerFunction and has access to all variables declared and defined in the outerFunction scope. In addition, the function defined inside another function as a closure will have access to variables declared in the global namespace.

Thus, the output of the code above would be:

outerArg = 7
outerFuncVar = x
innerArg = 5
innerFuncVar = y
globalVar = abc



Discussion

No Comment Found