Posted on Leave a comment

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);
Leave a Reply

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