In some programming languages like C, each piece of code within curly braces has its own scope, and variables are not visible outside the code segment where they are declared. We call this block-level scope ( block scope), and there is no block-level scope in JavaScript. Instead, JavaScript uses function scope: a variable is defined within the body of the function in which it is declared, as well as within the body of any functions within which it is nested. In the following code, i, j and k defined in different positions are all defined in the same scope
function text(o)
{
var i=0;
alert(typeof o);
If(typeof o == "string")
{
var j=0;
for(var k=0;k<10;k )
alert(k);//Output 0-9
alert(k);//output 10
}
alert(j);//output 0
}
The function scope of JavaScript means that all variables declared inside the function are always visible within the function body. Interestingly, this means that the variable is already available before it is even declared. This feature of JavaScript is informally called hoisting, that is, all variables declared in the JavaScript function body (not involving assignment) are "advanced" to the top of the function body. Look at the following code
function globals()
{
alert(global);//undefined
var global="hello QDao";
alert(global);//hello QDao
}
Due to the characteristics of function scope, local variables are always defined in the entire function body, which means that variables within the function body cover global variables with the same name. However, local variables are not actually assigned until the program executes the var statement. Therefore, the above process is equivalent to: "advancing" the variable declaration within the function to the top of the function body, while leaving the variable initialization at the original position. :
function globals()
{
var global;
alert(global);//undefined
global="hello QDao";
alert(global);//hello QDao
}