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

Variable shadow question

One of the questions regarding variable shadows asked the output of var person = "Jim";

Function whosGotTheFunc () {
    person = "Andrew";
}

person = "Nick";

whosGotTheFunc();

console.log(person);

The answer is Andrew yet I can't figure out why despite re watching the video three times.

3 Answers

2 things:

  • variables without var keyword are global
  • when you re-use a global variable you are actually re-assigning its value

If you are still a little fuzzy on this check out this article on scope from Daily JS.

Thanks the article helped a ton.

Thanks for the quick reply.

Hi! I had a question about this same thing. I understand when a variable is written without "var" preceding it, it becomes globally accessible regardless if it is written in a function or not. In the quiz question above, however, the variables Andrew and Nick are both written without var. So, wouldn't Nick print on the console.log?My logic is that the global variable person with the value Andrew would have been overwritten by Nick because the global variable person value "Nick" comes after "Andrew"? Please clarify! Thanks :)