Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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";



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

11,940 Points

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