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

A Simple Javascript Question...

There is a challenge question at the end of the Variables section in Javascript Foundations…It's a simple question but I'm not sure I understand it. Here's the code…

var color = "red";

function example () {
  var color = "blue";
}

example()

alert(color);

so, what I think is happening is that there are 2 variables called color being created, one outside the function, and one inside the function. The one outside the function is holding the value "red and the one inside the function is holding the value "blue". But what I don't get is what the Alert is doing? I'm guessing an Alert screen is popping up with the value of color, but which one is it taking? I thought it would be taking "red" because it can't access "blue" but I think I'm wrong. Could someone explain?

1 Answer

Sreng Hong
Sreng Hong
15,083 Points

Hi Robin, I tested on my console already. The right answer is "red".

The variable that declared on the first line is a global variable and the other is a local variable, so there aren't related. It's two different variables.

I think you might confused with the other question that look like this:

var color = "red";

function example () {
  color = "blue";
}

example()

alert(color);

So this one is different, because the variable that declared in the function didn't use var key word. It will modify the global one. The answer should be output "blue".

If you need more help, please tell me.

Thank you Sreng for the explanation … it really helps!