简体   繁体   中英

Why variable is undefined as I declared globally?

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) ?

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);
 }

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM