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 trialLuqman Shah
3,016 PointsGiven 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
28,407 PointsThe 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.
Luqman Shah
3,016 PointsLuqman Shah
3,016 PointsThank you!