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 trialGary Christie
5,151 PointsI 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
notf0und
11,940 PointsIn 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:
- person = "Jim"
- person = "Nick"
- 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.
David Tonge
Courses Plus Student 45,640 PointsIt works that way because without explicitly assigning a variable in a function without the "var" keyword it remains global