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

Hoisting

I don't get why this results in red instead of blue.

var color = "red";

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

example()

alert(color);

If example() ran, shouldn't color be "blue"?

3 Answers

I'm working on JavaScript myself so I can't tell you necessarily why it does this, but your var color = "blue"; should instead be color = blue; since you've already declared the variable. This would give you the proper output of blue.

What I'm thinking is that by stating var color = "blue"; you are creating a new variable called color that resides only within the scope of the example function. By stating color = blue; you are effectively pulling in the existing variable from outside of the function's scope and modifying it. I may be wrong.

I guess when the function example runs, it's blue. Then when alert runs, it doesn't pull from the function. It goes for the global variable.

I think Rachel's correct. The color is blue only within the "example" function and not outside it.

Using console.log to output the value for "color" at certain points you can see how it changes:

var color = "red";
console.log(color);  // will log "red"

function example() {
  var color = "blue";
  console.log(color);  // will log "blue" when the function is run
}

example(); // runs the function (will log "blue" as the console.log was called inside the function)

console.log(color);  // will log "red" as the function is no longer running

var color = "blue";
console.log(color);  // will log "blue" as we have re-declared "color" outside of any functions

Thanks for the clarity, Tom!

I think actually it is because you are assigning the VAR here. I just completed this and I remember you really have to keep in mind Scope! Also your eyes pealed :) I believe if i am seeing this right that you have defined that color within that function. so that variable is specific to that function. If you were to just define

color = blue. this would be a global change and I believe this is what your color would be :)