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

Source: Internet
Author: User

Declare a function, such as declaring a variable.

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.

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

How to use the var keyword in javascript

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.