Can someone help me understand why the value of x is 'undefined'?
var x = 100;
function test() {
if(false) {
var x = 199;
}
alert(x);
}
test();
Can someone help me understand why the value of x is 'undefined'?
var x = 100;
function test() {
if(false) {
var x = 199;
}
alert(x);
}
test();
When you define a new variable inside your if it is visible only inside it.
Considering that you declare again the variable x by writing var before, it become a variable visible only inside the if.
By removing that var, it will be changed if the if verifies and the alert will always work.
var x = 100;
function test() {
if(false) {
x = 199;
}
//alert(x);
console.log(x);
}
test();