i have seen this below link and answer but i am confused....
var color = "black";
var r = function (x, y) {
if(y == 1){
var color = "red"; //refers to local color, here color points to red color in memory
} else {
console.log('inside else block');
color = "red color";//refers to global color, here color points to red color in memory
}
//var color = "red color"; //refers to local color, here color points to red color in memory
//color = "red";//refers to global color, here color points to red color in memory
if (x > 2 ){
return x*2;
} else {
return x * x;
}
}
r(5, 2);
console.log(color);
but the output is black
instead of red color
which i expected....since inside the else
block it is referring to the global variable right?
without the if
block in there i get red
, as expected (see below code)....
if it is only function
scope then how does the value change in the above scenario?
var color = "black";
var r = function (x, y) {
//var color = "red color"; //refers to local color, here color points to red color in memory
color = "red";//refers to global color, here color points to red color in memory
if (x > 2 ){
return x*2;
} else {
return x * x;
}
}
r(5, 2);
console.log(color);
From msdn,
JavaScript does not support block scope (in which a set of braces {. . .} defines a new scope), except in the special case of block-scoped variables