Home >Web Front-end >JS Tutorial >Why do we need to add the var keyword when declaring variables in JavaScript_javascript tips
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.
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.