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

JavaScript JavaScript Foundations Variables Shadowing

Surendra Kulkarni
Surendra Kulkarni
6,826 Points


In the code below:

var person = "Jim";

function whosGotTheFunc() {
    person = "Andrew";

person = "Nick";



Ans: Andrew. My Q is outside of function var(global) person has be reassigned to "Nick" So the ans should be "Nick"?

2 Answers

Yes, the global variable person has been reassigned to "Nick" but in the next line, it gets reassigned to "Andrew" by calling the whosGotTheFunct() function.

In this case, the function is not declaring a variable in its local scope (no var declaration), so instead, it's modifying the variable in the global scope.

The scopes are nested in JavaScript. Once the whosGotTheFunc() function is called, the JavaScript engine checks the scope to see if there is a local variable called person. Since there is no such local variable, it checks the scope that's one level above it (or just outside of this scope). In this case, this is the global scope. Global scope returns that there is a variable person declared in it, and the engine assigns the value "Andrew" to that variable.