I am trying to understand how the following java script code works. I have global variable called color that stores 'blue'; I am calling printColor() that simple prints the color. What i don't understand is why the color is undefined when i am defining a new local variable called color in the function. If you uncomment the local color variable declaration below, the color is undefined.
var color = 'blue';
printColor();
function printColor(){
document.write(color);
//var color = "green";
}
var color; document.write(color); color = "green";. You're redefining a localcolorvariable, and it's being hoistedvar color = "green";line is commented out. That's fine, whendocument.write(color)executes, it looks in the current scope and doesn't find acolorvariable. So it looks up the scope chain and finds it in the parent scope, so it can print "blue". When you redeclare a local variable by the same name, it shadows the parent scope's variable, and hoisting is causing problems. I edited my last comment with more stuff too