A detailed description of the use of the Var keyword in javascript

Source: Internet
Author: User

Role
Declare a function, such as declaring a variable.
Grammar 

?
1 varc = 1;

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.

?
12345678 <script type="text/javascript">   functionDefine() {     a = 2;   }   functionHello() {     alert(a);   } </script>


As the code shows, after running the function define (), 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 a variable, but if you write the variable name directly without the keyword, and then assign it to it, JavaScript does not give an error, and it automatically declares the variable. Does it mean that the Var in JavaScript is an extra thing? Obviously not!

Take a look at the following code:

?
12345678 str1 = ‘Hello JavaScript!‘;functionfun1() { 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.

Then make a slight change to the above code:

?
12345678 str1 = ‘Hello JavaScript!‘;functionfun1() { var str1 = ‘Hello Java!‘;}fun1();alert(str1);// 弹出 Hello JavaScript!

See no, the value of str1 is not changed by the function fun1.

Obviously, the VAR keyword affects the scope of the variable.

Outside the function: variables are global variables, whether or not they are declared with Var.

Inside the function: If the variable does not use the var keyword declaration, then it is a global variable, only with the Var keyword declared, is the local variable.
Conclusion

To avoid potential risks, be sure to use the VAR keyword to declare variables.

How to use the var keyword in javascript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.