-2

I was playing aroun and found interessting thing

var x = "x";
function a (){
    var x = "y";
  if(1){
    var x = "g";
    alert(x);
  }
  alert(x)
}

a()

why does this output "g" , "g" insted of "g" , "y" ? The if creates another block scope and x is local variable inside it which means when i get out of the if block , the outer x ( which equals "y" ) should be printed.

Dingo
  • 331
  • 2
  • 3
  • 10

1 Answers1

0

The reason is the variable x has a function level scope and the latest value set to the variable is "g". And so you it alerted twice with same value of x "g".

Macfer Ann
  • 153
  • 1
  • 9