Error using Var in javascript creates Undefined_javascript tips

Source: Internet
Author: User

In JavaScript, depending on the scope of the variable's function, divided into local and global variables, the directly defined variables are global variables, global variables can be accessed by all scripts; the variables defined in the function are local variables, and local variables are valid only within the function.
If global and local variables use the same variable name, local variables will overwrite global variables.
Example code:

 <! DOCTYPE html>  
 

The result of the run is this:
Click Test1 to eject the local variable.
Click Test2, eject Undefined, and then eject the local variable

Click Test3, pop the global variable, and then eject the local variable

That's where the difference between using Var and not using it is:
If you use Var, the program forces a new variable to be defined.
if Var is not used, the system will first search for the existence of the variable in the current context, and redefine a new variable only if it does not exist.

In Test3, the variable A is a global variable, the first time the global variable is directly exported, and the second is used directly after the global variable is assigned a value.
In Test1 and Test2, a new variable with the same name is defined using Var in a function, which causes the variables in the functions to overwrite the global variable. So in Test2: the first output of a is a local variable A that has already been overwritten, but the initial value is not given, so there is a undefined result. The use of variables in this way is actually wrong and should be avoided.

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.