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

Shadowing

In the quiz the question is :

What will console log out in the following code?

var person = "Jim";

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

person = "Nick";

whosGotTheFunc();

console.log(person);

Now since "person" is defined as a global variable and the other two are not defined, then each time the name changes, the variable should change - witch is why choose "Nick". But they say it is incorrect.

I am confused!

2 Answers

It's incorrect because you called the function whosGotTheFunc() after Nick was defined. Because the function is called after Andrew takes place of Nick.

// variable person defined as Jim
var person = "Jim";

// function is defined, but not called, so person does not switch to Andrew.
function whosGotTheFunc() { person = "Andrew"; }

// Person is set to Nick
person = "Nick";

// Function is called and because it is called person is assigned to Andrew
whosGotTheFunc();

Thanks i understand!