In some programming languages like C, each piece of code within the curly braces has its own scope, and the variables are invisible beyond the declaration of their code snippet, which we call block-level scopes, and no block-level scopes in JavaScript. Instead, JavaScript uses function scopes: variables are defined in the body of the function that declares it and in any function that is nested within the function body. In the following code, I,J and K, defined in different locations, are defined in the same scope
Copy Code code as follows:
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 is that all variables declared inside a function are always visible in the body of the function. Interestingly, this means that the variable is even available before it is declared. This feature of JavaScript is informally called Declaration advance (hoisting), which is that all variables declared in the function body of JavaScript (not involving assignment) are "advanced" to the top of the function body. Look at the following code
Copy Code code as follows:
var global= "Globas";
function Globals ()
{
alert (global);//undefined
var global= "Hello Qdao";
alert (global);//hello Qdao
}
Because of the nature of the function scope, the local variable is always defined throughout the function body, that is, the variable in the function body obscures the global variable with the same name. Although the local variable is actually assigned when the program executes to the VAR statement, the procedure above is equivalent to declaring the variable in the function "ahead" to the top of the function body, leaving the colleague variable initialized in its original position:
Copy Code code as follows:
var global= "Globas";
function Globals ()
{
var global;
alert (global);//undefined
global= "Hello Qdao";
alert (global);//hello Qdao
}