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 Basics (Retired) Creating Reusable Code with Functions Review: Scope

Robert Rydlewski
Robert Rydlewski
3,828 Points

please help me understand it

1st Quiz: Given the code below, what appears in the alert dialogue when this program runs? 


var message = "Welcome!";
function setMessage() {
  message = "Go away!";
}
setMessage();
alert(message);

Answer “Go away!”

Treehouse - "Because the var keyword isn't used to declare a message variable inside the function, the function overwrites the value in the global variable message"

My understanding - "ok so the message variable inside the function, the function overwrites the value in the global variable message"

But the next question just give me exactly opposite information :(

2nd quiz: Given the code below, what appears in the alert dialogue when this program runs? 

var name = "Trish";
function setName() {
  var name = "Sarah";
}
setName();
alert(name);

Answer: “Trish”  The name variable outside the function is a global variable, so the alert() (which is also outside the function) accesses global variable.

Me " What !!??? how come in the previous question the variable was outside the function and it was told because function overwrite the value but this time the var " Trish" is the same in outside function in the global scope... How come 2 theme code but 2 different answers"

Help me understand the difference between those 2.

1 Answer

Mark Wilkowske
PLUS
Mark Wilkowske
Courses Plus Student 18,131 Points

Hi Robert, var always means new variable and try reading variables from right to left - that helped me. anyway, so the difference is var is used once in the first script and that makes 'message' a global variable.

In the second script var is used twice so 'name' is global outside the function but inside the function a new 'name' variable is local and Sarah should go into 'name'. Try this in the console: if you want to see Sarah and not Trish then move alert(name); inside the function. ;)

Hope this helps you out

Robert Rydlewski
Robert Rydlewski
3,828 Points

Thanks Mark... I slowly start understanding :) I was about to give up but your explanation gives me some light in the tunnel lol.. Anyhow, I have to play with it a litle bit in the console as you mention.. Thank's again Your the man, I appreciate your help, Enjoy rest of your day buddy :)