Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
David Trejo
19,914 PointsScope Chain Question
Hello,
I have a question about how this script works. I am trying to understand why "grandparent();", "parent();", and "child();" are needed for console.log in the child function to work.
var myVar = "A global variable";
function grandparent(){
function parent(){
var myVar = "Variable local to parent scope";
function child(){
console.log(myVar);
}
child();
}
parent();
}
grandparent();
1 Answer
Casey Ydenberg
15,622 Pointsfunction parent(){
var myVar = "Variable local to parent scope";
function child(){
console.log(myVar);
}
child();
}
parent();
Will work. However
var myVar = "A global variable";
function grandparent(){
function parent(){
var myVar = "Variable local to parent scope";
function child(){
console.log(myVar);
}
child();
}
}
parent();
will not. The variables and functions defined within grandparent cannot be accessed by the scope outside of it.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsHi David,
Could you try clarifying what you mean in your question? Are you asking why the console.log outputs what it does?
Maybe if you can show the context of where this code came from it will help.