var a = 10;
sayHi();
function sayHi()
{
var a = a + 10;
alert(a);
return a;
}
alert(a);
alert(sayHi()+10);
why the above result is not 20 and 30? i feel the first is 20 , then 30.in sayHi() function, there is a line var a; i don’t know why the a is undefined。 thank you
Because a is defined in the global scope and can’t be reached from within your function. If you want the function to use that variable you need to pass it as a parameter, like so
var a = 10;
a = sayHi(a);
function sayHi(a) {
var a += 10;
alert(a);
return a;
}
alert(a);
alert(sayHi(a)+10);
Basically you now have two different a variables; one lives within the global scope while to other lives only within the function sayHi. This is probably easier to understand if the function uses a different variable name:
var a = 10;
a = sayHi(a);
function sayHi(b) {
var b += 10;
alert(b);
return b;
}
alert(a);
alert(sayHi(a)+10);
This is exactly the same as the above but I now use a different variable within the function; semantically they’re the same thing.