Tag: CTI RET cannot run variable declaration variable a local variable func
has been the variable promotion is relatively vague, today specifically read this knowledge point, summed up.
1, for the simplest example of what is a variable promotion bar.
function foo () { console.log (x); // undefined var x =n; Console.log (x) // }foo ();
Since the variable declaration is promoted, the above code is actually equivalent to
function foo () { var x; Console.log (x); // undefined x =N; Console.log (x) // }foo ();
As you can see, the variable promotion is actually the promotion of the variable declaration, and the value of the variable is not promoted.
Now change the code above.
var x = 123; function foo () { console.log (x); // undefined var x =N; Console.log (x) /// // 123 Here The result is 123, Because the variable x declared inside the function has the same name as the function, but because it is declared within the function and with the keyword VAR, the x inside the function is just a local variable that cannot be accessed outside the function.
2. Use the return keyword before the variable declaration within the function.
function too () { console.log (y// undefined* y = ten; Console.log (y+ "* *"); // 10** return; // statements after return within a function do not execute Console.log (y+ "* * *"); var y = 2; Console.log (y+ "* * *")}too ();
Because the variable declaration is promoted and the return keyword is used within the function, the statement following the return of the function does not execute. So the above statement is equivalent to
function too () { var y; Console.log (y// undefined* y = ten; Console.log (y+ "* *"); // 10** }too ();
3. Declare variables within a control statement (such as in a for loop or if statement)
(1), declare variables within a for statement:
for (var i=0;i<5;i++) {}console.log (i) // 5
After running, you can see that the variables declared within the For statement can still be used outside the statement.
(2) Declaration of variables within the IF statement:
if (+) { var x = +;} Console.log (x) //
Once run, you can see that the variables declared within the IF statement can still be used outside of the IF statement.
(3), declare a variable with the same name inside the IF statement:
var x = 123; if (+) { var x =+//
Once run, you can see that the variables inside the IF statement overwrite the variables declared outside the IF statement.
JavaScript variable declaration and promotion