Because JavaScript does not have the concept of block-level scopes, the variables defined in the block statement are actually created in the containing function rather than in the statement.
Such as:
function Outputnumbers (count) {for (var i=0; i< count; i++) { alert (i); } alert (i);}
A For loop is defined in this function, and the initial value of the variable i is set to 0. In Java, C + + and other languages, the variable i is only defined in the statement block for the For loop, and once the loop is finished, the variable i is destroyed. In JavaScript, however, the variable i is defined in the Outpunumbers () activity object, so you can access it from within the function, starting with its definition. Even if you re-declare the same variable incorrectly, it doesn't change its value.
function Outputnumbers (count) {for (var i=0; i< count; i++) { alert (i); } var i; Re-declaring Variable alert (i); Count
JavaScript never tells you whether the same variable is declared more than once; in this case, it ignores the subsequent declarations, but performs the initialization of the variables in subsequent declarations. Anonymous functions can be used to mimic block-level scopes and avoid this problem.
(function () { //This is a block-level scope}) ()
The above code defines and immediately invokes an anonymous function. Include a function declaration in a pair of parentheses to indicate that it is actually a function expression. Another pair of parentheses immediately following it calls the function,
Another method:
var someFunction = function () { //This is a block-level scope};somefunction ();
The above example defines a function and then calls it immediately. The way to define a function is to create an anonymous function and assign the anonymous function to the variable somefunction. The way to call a function is to add a pair of parentheses after the function name, but note that the function value does not replace the function name, as
function () { //This is a block-level scope} ();
This results in a syntax error because JavaScript treats the Function keyword as the beginning of a declaration of functions, and the function declaration cannot have parentheses after it. Parentheses can be followed by an expression
Javascirpt How to mimic block-level scopes (JS elevation notes)