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

Ryan B.
Ryan B.
3,236 Points

Local/Global Scopes

Given the code below, what appears in the alert dialogue when this program runs? In the example below var message='Welcome!' is the global variable which is overwritten by the local scope message = 'Go Away!'. Even if we added the keyword VAR to message = 'Go Away!' so it reads var message='Go Away!' the answer would still remain B). "Go Away" because the var was renamed/decalred inside the function. Does this sound correct or is there something I am missing? Hope I'm not confusing myself. Thx in Advance for the help.

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

A)."Welcome" B)."Go Away"

*B is the correct answer.

Well done! 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.

1 Answer

yes you are understanding this correctly, the local scope message places the global scope message, its just like defining any other variable locally or globally.