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

Luqman Shah
Luqman Shah
3,016 Points

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);

Why will it be Trish? Because the function can't access the alert dialog as it's in the global scope? If it were re-written like this...

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

...only then will Sarah appear in the alert dialog? Now this sort of confuses my understanding of the global scope, I thought that because function setName() was declared first, the alert dialog will display whatever the value of name is within the function.

1 Answer

Matthew Long
Matthew Long
28,407 Points

The first one displays "Trish" because the function creates a new variable name.

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

If the var keyword isn't used to declare a name variable inside the function, the function overwrites the value in the global variable name.

The second one is just a function to alert the variable name. Since the alert is inside the function it will always alert the name inside the function.