Excerpt from the authoritative guide to JavaScript P57
The scope of a variable is the area in the program's source code that defines the variable.
Local variables: Variables declared inside a function are local variables, and function arguments are local variables.
Global variables: Global variables have global scope and are defined everywhere in the JavaScript code.
In the body of a function, a local variable takes precedence over a global variable of the same name.
You can declare the code for a global variable without writing Var, but declaring a local variable must use the var statement.
If Var is not applicable in a local variable, the value of the global variable may be changed or a global variable is declared.
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 are called block-level scopes, and there is no block-level scope in JavaScript. JavaScript uses the function scope instead, and the variables are defined in the body of the function that declares them, and in any function in which the body of the function is nested.
functionTestscope (o) {vari = 0; if(typeofo = = "Object") { varj = 10; for(varK =0;k<10;k++) { //Console.log (k);} console.log ("K" +k); } console.log ("J" +j); A (); functionA () {Console.log ("Inner function K" +k); Console.log ("Inner function J" +j); } }
Console printing
The function scope of JavaScript is that all variables declared within a function are always visible in the function body, which means that the variable is even available before the declaration. This feature of JavaScript is informally called declaration in advance, i.e. all variables declared in the JavaScript function ( but not related to assignment ) are "advanced" to the top of the function body.
var scope = "global"; function f () { // var scope = "local"; Console.log (scope); }
Equivalent to
var scope = "global"; function f () { var scope; // undefined Scope = "local"; Console.log (scope); }
In a block-scoped programming language, it is a very good programming practice to have variable declarations and code that uses variables as close to each other in a narrow scope as possible. Since JavaScript does not have block-level scopes, developers deliberately place variable declarations on top of the function body, which makes the source very clear about the actual variable scope.
JS variable Scope