access outer function variable in inner functions

50 Views Asked by At
function Outer(){
var a=10;
function Inner(){
var a = 20;
console.log(a);
}
Inner();
}
Outer();

In this codek I want the inner function to print the value of outer function's a(i.e 10). How do I achieve this?

1

There are 1 best solutions below

2
On

When you delcare var a = 20; on the fourth line above, you're redeclaring a variable that is already in scope and assigning it a new value. So the new value is what you get. If you remove that declaration, the name a will refer to the variable declaration in the outer scope and you'll get 10.