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

What will console log out in the following code?

The answer to the code written below is not making any sense to me. The question is as follows:

What will console log out in the following code?

var person = "Jim";

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

person = "Nick";

whosGotTheFunc();

console.log(person);

The quiz says that the answer is Andrew. Shouldn't the answer be Nick because person = "Nick"; was written above console.log(person); and after function whosGotTheFuc()?

Wasn't the global variable redefined as Nick?

Any input would be helpful.

Thanks!

3 Answers

The function whosGotTheFunc doesn't do anything until it's called.

And it's called after person = "Nick"; and before the console.log.

Once it's called, it sets the value of the global person variable to "Andrew" (because there's no var keyword in front of it, so it's not a local variable).

That's why the console.log prints out Andrew.

For a (big) clue, try putting "var" in front of both instances of "person", and then log it out to the console.

Got it! Makes perfect sense! Thanks for clarification! I appreciate your help!