In some C-like programming languages, each piece of code within the curly braces has its own scope, and the variables are not visible outside of the code snippet that declares them, and we call it block scope, which does not have block-level scopes in JavaScript. JavaScript has instead used the function scope: variables are defined in the body of the function that declares them, and in any function within which the body of the function is nested. In the above code, variables are defined in different locations i,j,k they are all within the same scope------The three variables are defined within the body of the function.
The function scope of JavaScript is that all variables declared within a function are always visible inside the function body. Interestingly, this thought that the variable was even available before the declaration. This feature of JavaScript is informally referred to as declaration advance (hoisting), which is that all variables declared in the JavaScript function (but not involving assignments) are advanced to the top of the function body.
Look at this code:
Run out of results: undefined local
You might mistakenly assume that the first line in the function outputs "global" because the code has not yet executed a place with a VAR statement declaring a local variable. In fact, because of the function scope, local variables are always defined throughout the function body, that is, local variables in the function body obscure global variables of the same name. However, the local variable is truly assigned only when the idiom executes to the VAR statement. Therefore, the above procedure is equivalent to: Advance the variable declaration within the function to the top of the function body, and the variable initialization remains in its original position:
In fact, the above code is this way.
var scope = "global"; (function f () { var scope;//variable is declared in advance to this place because there is no assignment, so the value is undefined console.log (scope);//undefined scope = " Local ";//This is the beginning of the assignment Console.log (scope);//value: Local }) ();
JavaScript function scopes and declarations in advance (3.10.1 page.57)