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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.