closure in JavaScript

Closure in JavaScript

While you create the JavaScript function within another function and the inner function  freely access all the variable of outer function. i.e.

How to create closure in JavaScript?

function ourterFun(i) {
    var var1 = 3;

    function innerFun(j) {
        console.log(i + j + (++var1)); // It will return the 16.
    }
    innerFun(10);
}

ourterFun(2); // Pass an argument 2

The output will get 16 because innerFun() function can access to the argument "i" & variable "var1" but both are define in the outerFun() function that is closure.

That means simply accessing variable outside of your scope create a closure.

// OR Other WAYS

function ourterFun(i) {
    var var1 = 3;

    return function (j) {
        console.log(i + j + (++var1)); // It will return the 16.
    }
}

var innerFun = ourterFun(2); // innerFun() function is now a closure.

innerFun(10);
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^