What is a “closure” in JavaScript? Explain with an example

Submitted 3 years, 2 months ago
Ticket #346
Views 231
Language/Framework Javascript
Priority Low
Status Closed

Thanks in advance

Submitted on Feb 10, 21
add a comment

1 Answer

Verified

A closure is an inner function that has access to the variables in the outer (enclosing) function’s scope chain. The closure has access to variables in three scopess:

  1. global variables.variable in its own scope,
  2. variables in the enclosing function’s scope, and
  3. variable in its own scope.
var globalVar = "abc";

(function outerFunc(outerArg) {
    var outerVar = 'x';
    
    (function innerFunc(innerArg) {
    var innerVar = 'y';
    
    console.log(
        "outerArg = " + outerArg + "\n" +
        "innerArg = " + innerArg + "\n" +
        "outerVar = " + outerVar + "\n" +
        "innerVar = " + innerVar + "\n" +
        "globalVar = " + globalVar);
    
    })(123);
})(456);

In the example, variables from innerFuncouterFunc, and the global namespace are all in scope in the innerFunc. The  output of the above code is

outerVar=x

innerVar=y

outerArg= 456

innerArg=123

globalVar=abc

Submitted 3 years, 2 months ago


Latest Blogs