var name="Jim";
var func=function(){
alert(name);
var name=true;
}
func();
var name="Jim";
var func=function(){
alert(name);
name=true;
}
func();
Two function has different results, can someone give me an explaination?
var name="Jim";
var func=function(){
alert(name);
var name=true;
}
func();
var name="Jim";
var func=function(){
alert(name);
name=true;
}
func();
Two function has different results, can someone give me an explaination?
The reason this occurs is from hoisting. The variable declaration inside of your function scope is hoisted to the top. What this means is that your first function actually looks like this
var name="Jim";
var func=function(){
var name;
alert(name);
name=true;
}
func();
Which should make it more clear why undefined is alerted.
See "var hoisting" for a more in depth explanation.
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
Your first function is equivalent to:
var name="Jim";
var func=function(){
var name;
alert(name);
name=true;
}
func();
because variable declarations are always put by Javascript at the beginning of the scope. Therefore, when alert(name)
is executed, name
is undefined
.
More information about scopes can be found in this answer.