Home >Web Front-end >JS Tutorial >Why do we need to add the var keyword when declaring variables in JavaScript_javascript tips

Why do we need to add the var keyword when declaring variables in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:34:521277browse

In JavaScript, var is used to declare variables, but this syntax is not strictly required. In many cases, we can use a variable directly without declaring it with var.

Copy code The code is as follows:

var x = "XX";
y="xxx";

And so on. There is a problem. For example, in a certain line of the code, I want to use a declared variable x. As a result, due to typing or spelling errors, the variable is written as y. The result is equivalent to an "implicit" declaration of a variable. y, in the actual programming process, this kind of error is sometimes difficult to find.
When you make this "implicit" declaration in the current context, the JavaScript engine will first look in the current context to see if this variable has been declared before. If not, then go to the previous context to find it. If it has not been found, , this variable will be finally declared on the window!
For example:

The code is as follows:

window. y = "hello"; 
function func(){ 
y = "OH, NO!!!"; 
} 
func(); 
alert(window.y); //#=> display "OH, NO!!!" 

When any layer in the context has such an "implicitly" defined variable, the variable in that layer will be modified without generating a new variable on the window. (This kind of bug is also quite annoying, especially when encapsulating more complex code)
For example:

The code is as follows:

var x = "window.x"; 
function a() { 
var x = "a's x"; 
var b = function() { 
var c = function() { 
//no var! 
x = "c's x:"; 
}; 
alert("before c run,the b.x:" + x); 
c(); 
alert("after c run, the b.x:" + x); 
}; 
alert("a.x is:" + x); 
b(); 
alert("after b function runed, the a.x is:" + x); 
}; 
alert("before a run, window.x:" + x); 
a(); 
alert("after a run, window.x:" + x); 

There are the following layers: window, func a, func b, func c are always hierarchically nested. window->a->b->c
In both window and a, the variable x is defined, but in b the variable is not defined. In c, an x ​​is declared 'implicitly', and the x ultimately modifies the value of the a variable.
Remember, in JavaScript, when declaring a variable, it must be preceded by var.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn