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 accessed by all scripts; the variables defined in the function are local variables, and local variables are only valid within the function.

If the global variable and the local variable use the same variable name, the local variable overrides the global variable.

Example code:

<! DOCTYPE html>

The result of the operation 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:

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 variable in the current context and redefine a new variable only if it does not exist.


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 an already covered local variable A, but does 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.