The use of the Var keyword in javascript-basic knowledge

Source: Internet
Author: User

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

var c = 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.

<script type= "Text/javascript" > 
  function Define () { 
    a = 2; 
  } 
  function Hello () { 
    alert (a); 
  } 


As the code shows, when the function define () is run, 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 variables, but if you do not use this keyword to write the variable name directly and then assign it to it, JavaScript will not give an error, it will automatically declare the variable. Does it mean that the Var in JavaScript is a superfluous thing? Obviously not!

Take a look at the following code:

str1 = ' Hello javascript! ';
function fun1 () {
 str1 = ' Hello java! ';
}
Fun1 ();
alert (str1);

Pop Up Hello java!

As you can see, after the function fun1 is called, the value of the STR1 is changed within the function.

The above code is slightly modified:

str1 = ' Hello javascript! ';
function fun1 () {
 var str1 = ' Hello java! ';
}
Fun1 ();
alert (str1);

Pop Up Hello javascript!

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

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

External function: variable whether or not the Var declaration is used, is a global variable.

Inside function: If the variable is not declared with the Var keyword, it is a global variable, and only if it is declared with the Var keyword, it is a local variable.
Conclusion

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


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.