Home >Web Front-end >JS Tutorial >What does var in js mean?
JavaScript is a literal scripting language. It is a dynamically typed, weakly typed, prototype-based language with built-in support for types. The var in js is used for declaration and can declare variables, etc. Let’s learn more about it with the editor below.
var 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 It 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(), variable a is declared as a global variable.
Variable a can be referenced in the Hello() function.
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 this variable.
Is it true 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!
You can see that 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 has not been changed by function fun1.
Obviously, the var keyword affects the scope of the variable.
#External function: Variables are global variables regardless of whether they are declared with var or not.
# Inside the function: If a variable is not declared using the var keyword, it is a global variable. Only when it is declared using the var keyword, it is a local variable.
Conclusion: In order to avoid potential risks, be sure to use the var keyword to declare variables.
The above is the detailed content of What does var in js mean?. For more information, please follow other related articles on the PHP Chinese website!