The difference between adding Var and not adding Var when javascript defines variables _ basics

Source: Internet
Author: User

One, the external is global, internal is local variable.

Second, add var as local variable (within the method), without VAR as global variable (once used in the method)

Copy Code code as follows:

<script type= "Text/javascript" >
var golbe= "global";
Test ();
function Test () {
var local= "local";
document.write (Golbe);
document.write (local);
}
document.write (Golbe);
document.write (local);
</script>

In the test method above, when the Var of the local variable is removed, the locality becomes a global variable, but it is not used locally as a whole, which is not valid for the global.

To verify this, I comment out the only code inside the test method that uses the local variable. The discovery is not printed outside.

Summary: Global variables can declare var without declaring Var, while defining global variables with or without the VAR keyword has little effect, but if the local variable is defined without the var keyword javascript interpreter interprets it as a global variable.

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.