JavaScript JavaScript Basics Creating Reusable Code with Functions Review: Scope

Robert Rydlewski
Robert Rydlewski
3,043 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
MOD
Mark Wilkowske
Treehouse Moderator 16,484 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,043 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 :)