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

What does var in js mean?

little bottle
Release: 2019-05-23 17:32:29
Original
16485 people have browsed it

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;
Copy after login

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>
Copy after login

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!
Copy after login

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!
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template