javascript, Unlike Java and c, is a non-type, weak-detection language. It does not need to declare variable types, and we can assign various types of data to the same variable as long as they are in the form of a Value.
JS variable type and declaration method, etc., This article no longer explain, the reader can refer to the relevant official documents
This article mainly introduces the JS variable and its scope
The scope of JS variables can be divided into: "global variables" and "local variables"
"global variables": declaring variables outside of a function
"local Variable": declares a variable in the body of the function and is accessible only within the body of the current function, such as: function () {var a = 0;}
Note: variables that are declared are generally not the Var keyword, and the directly assigned variable is a global variable
Here are some small examples to familiarize yourself With.
1. Function Test () {
A = 30;
var B = 20;
}
Test ();
Console.log ("a=" +a); It's obvious here that A is a global variable
Console.log ("b=" +b);//b is a local variable, so in the function test out of the box, the hint is undefined
2.
var a = 1;
Function Test () {
Console.log ("a=" +a); Here A is undefined
The variables declared in the/* function are defined throughout the Function. If there is a defined variable inside the function, even if it is output before the definition, it executes the later definition statement and then determines the output, so that the declared variable will work in the whole Function. */
var a = 2;
}
Test ();
3.
For the comparison of two small examples:
var a; function Fun () {a = "global";} console.log (a);//output undefined
var a; function Fun () {a = "global";}
Fun (); Console.log (a);//output Global
For these two small examples, the only difference is that one executes the fun function and one is not executed;
If it is
var a;console.log (a);//because A is defined but not initialized, the output undefined
and function Fun () {...} The initialization operation is in the scope of the fun function, and if you do not execute the fun ()
4, the function domain takes precedence over the global domain, therefore the local variable a will overwrite the global variable a
var a=1;
Function Main () {
var a=2;//local variables
Console.log (A);//2
}
Main ();
Console.log (A);//1
5. JavaScript does not have a block-level scope
Function Test () {
for (var i = 0; i < 3; i++) {
i=0,1,2, exit loop when last execution to i=3
}
Console.log (I);//3
}
Test ();
Equivalent
Function Test () {
var i;
For (i = 0; I < 3; i++) {
i=0,1,2, exit loop when last execution to i=3
}
Console.log (I);//3
}
Test ();