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

Help: Review- Scope

I don't understand...

Tommy Gebru
Tommy Gebru
30,164 Points

Hey Ashok,

What are you having trouble with? You have posted to the Forum a few times but there was not enough information, to describe your question. Please take the time to be really detailed so students can help you faster and provide strong answers

1 Answer

Aman Mundra
Aman Mundra
2,755 Points

If I'm following correctly, I believe your question references the quiz question that has the following code:

var message = "Welcome!";

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

setMessage();
alert(message);

The question asks what will be posted on the alert message. The last line of the code states that whatever is stored in the variable called "message" is what will be posted in the alert. So now we have to figure out what is stored in the variable message.

Reading from the top of the code downwards, initially, the variable message has the string "Welcome!" stored in it.

However, the next few lines of code (specifically the setMessage function) changes the value of the variable message; it changes message to equal "Go away!"). So it is "Go away!" that will be printed in the alert message.

The key here is that within the setMessage function, they didn't declare a new variable 'message' (they just referenced the already declared variable message). And therefore, anytime that the setMessage function is called, it updates the old variable 'message' to say "Go away!"

Because the setMessage() function was called on the second to last line of code, the variable message is holding the String "Go away!" in it right before the alert is then posted.

Hope that helps.