JavaScript variable declaration, javascript variable Declaration
The declaration and initialization are different.
Statement
Var joe; // the declaration
Initialization
Joe = 'plumber'; // the initialization
Claim front
You can declare variables through var anywhere in the function. They will act like declarations at the top of the function. This behavior is called hoisting (front/top resolution/pre-resolution ). When you use a variable and then re-declare it in the function, logical errors may occur. Let's look at the example below:
var myname = "global";(function() { alert(myname); var myname = "local"; alert(myname);})();
In this example, you may think that the first alert is "global" and the second alert is "local ". This expectation is understandable, because at the first alert, myname was not declared. At this time, the function will naturally look at the global variable myname. However, this is not actually the case. The first alert will pop up "undefined", because myname is treated as a local variable of the function (although declared later), all the variable declarations are prefixed to the top of the function. Therefore, to avoid such confusion, it is best to declare all the variables you want to use in advance.
The execution of the above code snippet will be like the following:
var myname = "global";(function() { var myname; alert(myname); myname = "local"; alert(myname);})();
Forget the side effects of var
Due to the two features of JavaScript, it is unexpected to create a global variable unconsciously. First, you can use variables without even declaring them. Second, JavaScript has an implicit global concept, meaning that any variables you do not declare will become a global object attribute. See the following code:
function sum(x, y) { result = x + y; result;}sum(1, 3);alert(result);
The result outside the function scope in this code is not declared, and the code still works normally. alert will pop up 4. If var is not used in the function variable, a global variable is generated, which is the Side effect of Forgetting var (Side Effects When Forgetting var ). Therefore, it is important to use as few global variables as possible if you want to become a good neighbor with other scripts.
The most important thing to minimize global variables is to always declare variables using var.