Why does JavaScript declare variables with the var keyword

  • 2020-03-30 04:03:10
  • OfStack

In JavaScript, var is used to declare variables, but this syntax is not strictly required, and many times, we can directly use a variable without var declaration.


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

And so on. There's a problem with this, for example, a line in the code, a declared variable x that I want to use, and it turns out that because of a typo or a spelling error, the variable is written as y, and it turns out that it implicitly declares a variable y, which is sometimes hard to find in actual programming.
When you make this "implicit" declaration in the current context, the JavaScript engine looks in the current context to see if the variable was previously declared. If not, it looks in the next context.
Such as:

The code is as follows:


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

When a variable is defined "implicitly" at any level of the context, the variable at that level is modified instead of generating a new variable on the window. (this kind of bug is also annoying, especially when it comes to encapsulating complex code.)
Such as:

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, all the way down to the nested levels. The window - > A - > B - > c
In both window and a, there is a defined variable x, which is not defined in b, and in c 'implicitly' declares an x, which ultimately modifies the value of the a variable.
Remember, in JavaScript, when you declare variables, you always add var.


Related articles: