2

I am just showing the value of a in alert but I am getting a is undefined why? I will explain the problem:

First I call function with false parameter, it show alert with a = 1;. But when I pass true as parameter, it first show alert 2 (as expected it is local) but when again it show 2? Third it say a is undefined?

function ab(p){
    a = 1;
    if(p){
        var a = 2
        alert(a)
    }
    alert(a)
}

ab(false);
alert(a);

Unexpected result when ab(true)?

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
Pallavi Sharma
  • 635
  • 2
  • 16
  • 45

3 Answers3

4

That is what called as variable hoisting. and actually the variable that you are thinking as a global one will be hoisted inside of that function and it would turn as a local one.

Compiler would consider your code like this,

function ab(p){
  var a;  //will be hoisted here.
  a=1;
  if(p){
     a=2;
     alert(a);
  }
  alert(a);
 }
Balachandran
  • 9,427
  • 1
  • 14
  • 25
2

That is not global. you have defined the variable in if condition. its context will remain inside if only. use :

function ab(p){
       a=1;
       if(p){
           a=2
           alert(a)
       }
       alert(a)
   }

ab(false);
 alert(a);

Working Demo

Milind Anantwar
  • 79,642
  • 23
  • 92
  • 120
1

You are using var inside your function, so JavaScript see your code as below (there is no matter where you use var, inside if or in loops or ...):

function ab(p) {
    var a=1;
    if (p) {
       a=2;
       alert(a);
    }

    alert(a);
}

ab(false);
alert(a);
dashtinejad
  • 6,127
  • 3
  • 26
  • 43