Role
declaring a function, such as declaring a variable.
Grammar
Omit Var
in JavaScript, if you omit the var keyword and assign it directly, the variable is a global variable, even if it is defined in a function.
<script type= "Text/javascript" >
function Define () {
a = 2;
}
function Hello () {
alert (a);
}
As the code shows, when the function define () is run, the variable A is declared as a global variable. You can refer to variable A in the Hello () function.
More specific examples
we all know that the Var keyword in JavaScript is used to declare variables, but if you do not use this keyword to write the variable name directly and then assign it to it, JavaScript will not give an error, it will automatically declare the variable. Does it mean that the Var in JavaScript is a superfluous thing? Obviously not!
Take a look at the following code:
str1 = ' Hello javascript! ';
function fun1 () {
str1 = ' Hello java! ';
}
Fun1 ();
alert (str1);
Pop Up Hello java!
As you can see, after the function fun1 is called, the value of the STR1 is changed within the function.
The above code is slightly modified:
str1 = ' Hello javascript! ';
function fun1 () {
var str1 = ' Hello java! ';
}
Fun1 ();
alert (str1);
Pop Up Hello javascript!
See no, the value of the str1 is not changed by the function fun1.
Obviously, the VAR keyword affects the scope of the variable.
External function: variable whether or not the Var declaration is used, is a global variable.
Inside function: If the variable is not declared with the Var keyword, it is a global variable, and only if it is declared with the Var keyword, it is a local variable.
Conclusion
To avoid potential risks, be sure to use the VAR keyword to declare variables.