Using a unique VAR statement at the top of a function is a recommended pattern, and the benefits are:
1, you can find all the variables in the same place.
2. Avoid the logic errors generated by using the variable before the variable declaration.
JavaScript allows you to write any number of VAR statements anywhere in the function, but they behave like declaring variables at the top of the function body, which is called "declaration ahead," which can cause logic errors when you use this variable before declaring a statement.
For JavaScript, once a variable is declared within a scope (in the same function), the variable is present throughout the scope, including where it precedes the Var declaration statement.
*/ Not familiar with the assumption that the first alert is global and the second is local. But the result is not so. * Analysis: The result of the first alert is not the ' global ' variable. Since MyName is declared within a function, all the variable declarations in this scope are advanced to the top of the function * i.e. Var myname, although defined later in the statement, the result of the first alert is undefined; * Therefore, to avoid similar procedural logic with "ambiguity", it is best to declare it together before use. */ myname = "global"; // global variable function Func () {alert (myname); // "undefined" var myname = "local" // "local"
3, you can be reminded to see whether the defined variables are local or global.
4, the amount of code less.
When you use a var to define multiple variables, separate them with commas, or you can initialize the variables directly.
function func () { var A, B, = a + b, = {}, i; }
JavaScript single VAR statement