Reputation: 655
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)
?
Upvotes: 2
Views: 101
Reputation: 6253
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);
Upvotes: 1
Reputation: 82241
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);
Upvotes: 2
Reputation: 9637
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);
}
Upvotes: 4