Home  >  Article  >  Web Front-end  >  What does var in js mean?

What does var in js mean?

little bottle
little bottleOriginal
2019-05-23 17:32:1416435browse

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.

What does var in js mean?

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 = &#39;Hello JavaScript!&#39;;
function fun1() {
 str1 = &#39;Hello Java!&#39;;
}
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 = &#39;Hello JavaScript!&#39;;
function fun1() {
 var str1 = &#39;Hello Java!&#39;;
}
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is Node.js fsNext article:What is Node.js fs