Subject not found.
1.

What Is Closure In Javascript?

Answer»

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

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);

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

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);



Discussion

No Comment Found