JavaScript variable declarations
Container JavaScript variables stored data is referred to. Create a new variable with the statement keywords and identifiers, known as variable declarations. Can be performed by keyword var variable declaration, an increase of ES6 let in, the const keyword syntax for declaring variables.
JavaScript variable declarations in advance
Function scope (function scope) in JavaScript that refers to all variables within a function var declared in the body of the function is always visible. All JavaScript variables characteristic of this statement is informally known in advance (hosting), that is, the JavaScript function in the statement (but do not involve the assignment) are "ahead" to the top of the function body.
var scope = "global"; function f() { console.log(scope);//=>"undefined" var scope = "local";// console.log(scope);//=>"local" }
Due to the nature of the function scope, local variables throughout the function body is always defined, that is to say, the body covered in the local variables of the same name global variables. Nevertheless, only when the program execution to the var statement, the local variables will not actually be assigned. Thus, the above process is equivalent to: declare function of the variable "early" functions to the top of the body, while the remaining variables are initialized at the original location:
scope = var "Global"; function F () { var scope; // at the top of the function of local variables declared console.log (scope); // variables exist, but its value is "undefined" scope = "local"; / / where it is initialized and assigned console.log (scope); // => where it has to our desired value }