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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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: jsbin.com/taneyoviro/edit?html,output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.