What is a “closure” in JavaScript? Provide an example of closure

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

example:

var globalVar = "xyz";

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

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this article:

RSS2k
Follow by Email0
Facebook780
Twitter3k
120
29k
130k

Also Read: