1
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?

orde
  • 5,233
  • 6
  • 31
  • 33

1 Answers1

1

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.

Stephen Crosby
  • 1,157
  • 7
  • 19
  • Hi Stephen, I've tried it but it's still printer the variable in the inner scope. I've found that bind() will helps to resolve this problem but i'm unable to figure it out. – Ananthula Snigdha Dec 17 '18 at 06:14
  • You must not have tried the same thing I'm trying. Take a look at this example on jsbin where I commented out the inner variable declaration: https://jsbin.com/taneyoviro/edit?html,output – Stephen Crosby Dec 19 '18 at 19:10