The scope of a variable is the area in the program's source code that defines the variable. Global Variables have global scope and are defined everywhere in the JavaScript code.
However, variables declared within a function are defined only within the function body. They are local variables and the scope is local. Function parameters are also local variables, they are defined only in the body.
in the body of a function, a local variable takes precedence over a global variable of the same name. If a local variable or function parameter declared within a function has the same name as a variable and a global variable,
The global is covered by local variables .
eg
var a= "AAAA";
(function () {
var a= "BBB";
Console.log (a);
})();
= Output bbbb;
In a generic programming language, each piece of code within the curly braces has its own scope, and the variables are not visible outside the code snippet that declares them. We call this block-level scope.
In JavaScript, however, there is no block-level scope. Instead, the function scope is used: variables are visible in the body of any function that declares their function body and the function's nesting the .
eg
(function test (O) {
var i=0;
if (typeof O = = "Object") {
var j=0;
for (var k=0; k<10;k++) {
Console.log (k); = 0~9
}
Console.log (k); =>10
}
Console.log (j);=> 0
})({});
The above example shows that the variables declared in the function body are always visible within the function body. This also means that the variable is even available before the declaration, which has an informal called function Variable declaration in advance
Javascrippt scope-function scope and declaration advanced "from the Javascript authoritative guide"