Javascript variable scope - variable undefined -
this question has answer here:
i trying understand how following java script code works. have global variable called color stores 'blue'; calling printcolor() simple prints color. don't understand why color undefined when defining new local variable called color in function. if uncomment local color variable declaration below, color undefined.
var color = 'blue'; printcolor(); function printcolor(){ document.write(color); //var color = "green"; }
you re-declaring variable color inside printcolor()
function, since declaration hoisted top overwrites @ start of function, hence see undefined
var color = 'blue'; function printcolor(){ document.write(color); //var color = "green"; } printcolor();
but if do:
function printcolor(){ document.write(color); //undefined var color = "green"; console.log(color); //shows green }
Comments
Post a Comment