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
  • 57,103
  • 20
  • 141
  • 208
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,567
  • 1
  • 16
  • 26
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
  • 81,290
  • 25
  • 94
  • 125
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,193
  • 4
  • 28
  • 44