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

I don't know why this is right?

He challenge question is: What will console log out in the following code?

var person = "Jim";

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

person = "Nick";

whosGotTheFunc();

console.log(person);

The Answer is Andrew. Why? I understnad that neither Nick or Andrew are Vars, but being that Nick is being assigned the Value of "person" after Andrew, I would think the answer would be Nick.

2 Answers

In the order of assigning values to the variable "person", the value "Andrew" was assigned last, in the whosGotTheFunc() function.

So to break it down more, this is the order of the program:

  1. person = "Jim"
  2. person = "Nick"
  3. the function "whosGotTheFunc()" is called, which executes all the code inside, therefore making person = "Andrew"

And that's why that works.

Edited for a bit more clarity.

It works that way because without explicitly assigning a variable in a function without the "var" keyword it remains global