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

Jacob Williams
Jacob Williams
10,915 Points

Why isn't it "Nick"?

I get all of this except why person doesn't become "Nick" at the end. It's in the global scope, you're not using var beforehand, so I get that, but shouldn't just saying person = "Nick" before console.log(person) make it log "Nick?" Same as when you say person = "..." within the scope of the function? Maybe I missed something...

Hi Jacob,

Which question are you referring to? They don't always come up in the same order.

2 Answers

Seth McCombs
Seth McCombs
16,767 Points

Hey Jacob, if I'm not mistaken, this question was answered here and if definitely shed some light on it for me!! Good luck!

Seth McCombs
Seth McCombs
16,767 Points

With that being said, if you're referring to the question I believe you are, that's because the "person" declaration is being set to "Andrew" inside the function, whereas the function is called AFTER it is set "Nick" outside the function. So the "Andrew" declaration happens last in the code before the console.log

Jacob Williams
Jacob Williams
10,915 Points

and yep! That's exactly where I went wrong, lol

Jacob Williams
Jacob Williams
10,915 Points

Thanks Seth, I got it. And I'll go ahead and answer Jason's question in case someone else sees this and has the (kind of obvious...) same problem I did:

//Question 1
var person = "Jim";

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

person = "Nick";

whosGotTheFunc();

console.log(person);
//solution: I understand that this should be Nick, which it is. Saying person = "Nick"; refers to the original global variable. It's final value is "Nick"



//Question 2, the one that threw me
var person = "Jim";

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

person = "Nick";

whosGotTheFunc();

console.log(person);

I was confused because I thought the answer should be "Nick" again. This code makes it "Andrew" because calling whosGotTheFunc(); at the end is the final change made to the global variable. I sometimes have trouble reading and processing code in the right order at first glance... still building that brain muscle.

Seth McCombs
Seth McCombs
16,767 Points

No worries! I'm pretty sure I stared at that question for a while before I got it. Coming from HTML and CSS, JS took some work for me! Bit by bit!