Function
Declaration function; such as declaring a variable.
Grammar
var c = 1;
Omit var
In JavaScript, if you omit the var keyword and assign a value directly, then this 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); } </script>
As shown in the code, after running the function Define(), the variable a is declared as a global variable. Variable a can be referenced 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 and directly write the variable name, and then assign it to it, JavaScript will not report an error, it will automatically declare the variable . Could it be that var in JavaScript is redundant? Obviously not!
Please look at the following code:
str1 = 'Hello JavaScript!'; function fun1() { str1 = 'Hello Java!'; } fun1(); alert(str1); // 弹出 Hello Java!
As you can see, after the function fun1 is called, the value of str1 is changed within the function.
Modify the above code slightly:
str1 = 'Hello JavaScript!'; function fun1() { var str1 = 'Hello Java!'; } fun1(); alert(str1); // 弹出 Hello JavaScript!
See, the value of str1 is not changed by function fun1.
Obviously, the var keyword affects the scope of the variable.
External to the function: Variables are global variables regardless of whether they are declared with var or not.
Inside the function: If a variable is not declared with the var keyword, it is a global variable. 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.