-1

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();
Ankush G
  • 989
  • 9
  • 14
Deepak
  • 9
  • 1
  • Because variables are local to the current function scope – Lennholm Aug 10 '17 at 12:48
  • 1
    https://stackoverflow.com/search?q=%5Bjavascript%5D+hoisting – deceze Aug 10 '17 at 12:49
  • @litelite The `x` outside of the function gets shadowed by the `x` declared inside the function – Lennholm Aug 10 '17 at 12:50
  • Even it is declared and assigned inside the `if(false)` statement Javascript run something called **hoisting**, that pop ups all the variables declared inside a closure in to the beginning of that closure. So the variable is assigned inside the `if` but it is really declared previously. As the code asks for the x value it prints Undefined. The x global variable is not taked in account because there is another with the same name declared inside the closure of the funcion test. Check https://www.w3schools.com/js/js_function_closures.asp and https://www.w3schools.com/js/js_hoisting.asp – jmtalarn Aug 10 '17 at 13:00

1 Answers1

0

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();
Sagar V
  • 12,158
  • 7
  • 41
  • 68
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32