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

nishnash
nishnash
6,267 Points

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

Lee Cockcroft
Lee Cockcroft
5,147 Points

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

2 Answers

nishnash
nishnash
6,267 Points

Thanks Lee,

Think i got it now..

andren
andren
28,558 Points

Yes 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.