16
Apr

How to differentiate outer variable with same name in javascript closures

Suppose the variable name in outerfunction is same as in inner function

function outer() {
var b = 10;
var a = 100;
function inner() {
b = 20; // this is same as outer function variable
console.log(“a= ” + a + ” b= ” + b);
}
return inner;
}

var x = outer();
x(); // executing x will respon b’s value from inner()

Following code demonstrates how to access outer()’s variable:
————————————————————–

function outer() {
var b = 10;
var a = 100;
function inner() {

inner.b = 20;
console.log(“a= ” + a + ” b= ” + b);
a++;
b++;
console.log(“a= ” + a + ” b= ” + inner.b);
}
return inner;
}

var x = outer();
x();

output:
——-

a= 100 b= 10
a= 101 b= 20