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 trialnishnash
6,267 PointsFunction Scope
Can somebody please help clarify the below??. Why is Trish the answer?? when we type setName(), are we not calling that function, thus replacing the var name to sarah ?
Quiz Question 3 of 5 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);
2 Answers
nishnash
6,267 PointsThanks Lee,
Think i got it now..
andren
28,558 PointsYes you are calling that function, but all that function does is create (that part is important) a variable called name and set it equal to "Sarah". This new variable is not the same name variable that was declared outside the function. It is an entirely new, entirely separate variable that just happens to share the same name as the other variable.
The reason why the name variable in the function is treated as a new variable rather than a reference to the existing variable is because the "var" keyword precedes it, var is used to declare a new variable that should exist within the current function. So in the end there are two "name" variables, one that exist outside the function (in the global scope) and one that exists within the setName function. And as mentioned before, those variables are the same in name only. As far as JavaScript is concerned they are entirely different things and do not affect each other in any way.
Lee Cockcroft
5,147 PointsLee Cockcroft
5,147 PointsBecause you haven't returned anything in the function.
The code below will alert "sarah" because you're returning the name variable.
if you just alert "name" this will go to the global variable and return trish!
To access the name variable in the function you must use the "setName" variable
Hope it makes sense
var name = "Trish";
function setName() { var name = "Sarah"; return name; } alert(setName());