Incorrect use of Var in javascript causes undefined

Source: Internet
Author: User

In JavaScript, depending on the scope of the variables are divided into local variables and global variables, the directly defined variables are global variables, global variables can be all the script access; the variables defined in the function are local variables, and local variables are only valid within the function.

Assuming that the global and local variables use the same variable name, the local variable overrides the global variable.

Sample code:

<! DOCTYPE html>

The result of the implementation is this:

Click Test1 to eject the local variable.

Click Test2, eject Undefined, and then pop the local variable

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


This is where the difference between using VAR and not being used is:

Assuming that Var is used, the program enforces a new variable.

Assuming that no Var is used, the system will first search the current context for the existence of the variable, and will only define a new variable once again without being present.


TEST3, the variable a used is a global variable, the first direct output of the global variable, the second is directly assigned to the global variable after use.

The use of Var in test1 and test2 to define new variables with the same name will cause the variables in the function to overwrite the global variables. So in Test2: the first output of a is already covered by the local variable A, but did not give the initial value, so there will be undefined this result. Using variables in this way is actually wrong and you should avoid them.



Incorrect use of Var in javascript causes undefined

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.