JavaScript defines a variable with Var and no var when the difference is discussed _ basics

Source: Internet
Author: User

Let's look at a piece of code first.

Function Show () { 
alert (ABC); 
} 
var abc= "DEFG"; 
Show ();

People who have experience in C + + or Java programming may say, "This program is dead, and the variable is defined behind the function that references the variable, and the bug will kill you." "Put it on the browser and run it, what's the result?" Perfect run! So let's just say what this is about--there's a difference between VAR and a variable that doesn't have a var definition.

1, no Var

To be concise, it is unsafe to omit Var when defining a variable, but it is legal. At this point, regardless of where the variable is defined, the interpreter gives the variable a global scope.

2, there are Var

Safe, lawful. The scope of the defined variable depends on where it is defined. As for what the scope is, see the "JavaScript scope" article in this blog.

In this way, the beginning of the problem can be solved. In the function is the definition of ABC, but the value is undefined, then ABC has a global scope, the function is only the value of the ABC update.

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.