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 trialJeremy Frimond
14,470 PointsConceptual: nesting variables inside other variables and their different outputs
I have two sets of code:
the First alerts the color blue upon loading the page.
var color = "red";
function example () {
color = "blue";
}
example()
alert(color);
The Second alerts the color red upon loading the page
var color= "red"
function example () {
var color = "blue";
}
example()
alert(color);
I understand that the difference is coming from putting "var" in the second piece of code, where in the first var is not put in front of blue. What I dont understand is how this affects the output of both codes and ultimately why we see one say blue and one say red. additionally, which is the better practice to use?
cheers
2 Answers
David Valles
18,487 PointsIn your first code snippet, you have declared and assigned a global variable "color". your function only assigns a value, so it uses global variable 'color'. thus blue is alerted.
In your second code snippet, your function has declared and assigned a value to a locally scoped variable called 'color'. this variable is not accessible outside the function and thus is different than your global variable of the same name. thus red is alerted.
key points to understand:
- declaration vs. assignment of variables
- global vs. local scope of variables
I believe its good practice to minimize the use of global variables.
Jeff Busch
19,287 PointsHi Jeremy,
Always use var when declaring variables. By not using var inside the function in the first example the variable color is now a global variable overwriting the variable var color = "red"; which is a global variable because it is declared outside of the function. In the second example I'm assuming you forgot the first variable declaration because the code as it is would produce an error: color is undefined. It will probably be a good idea to rrewatch the video to better understand variable scope.
Jeff
Jeremy Frimond
14,470 PointsJeff Busch hey sorry I was copying and pasting and forgot to add in the initial declaration I have added it in now if it will make more sense to the question I am asking?