Analysis of local variables and global variables in javascript and javascript

Source: Internet
Author: User

Analysis of local variables and global variables in javascript and javascript

Recently, I have a group of questions about the interview and basic knowledge about global variables and local variables:
Fun foo (){
Var a = B = 0;

}
Let's select the values of a and B separately. Maybe we don't take a closer look. We may think of a and B as local variables. The value is 0. In fact, a is a local variable, B is a global variable. This is mainly because the operator priority from right to left is the same as that of the css selector that we usually Parse in the browser, a higher priority is expression B = 0. At this time, B is not declared, and the return value of the expression is 0. It is assigned to the local variable a declared by var, as shown below:
Var a = (B = 0 );
If all the variables with chained values are declared, unexpected global variables will not be created, such
Function foo (){
Var a, B;
A = B = 0; // both are local variables
}

Global variables created using var (these variables are created outside the function) cannot be deleted;
You can delete the hidden global variables created without using var (though embedded in the function;

Although variable declaration can be anywhere in the document, it is a good habit to declare variables before all JavaScript code and initialize and assign values to variables. The variable is also declared inside the function and then referenced.
In variable query, accessing local variables is faster than global variables, because you do not need to search for the scope chain. Local variables are automatically cleared and destroyed when the function is executed, without occupying the memory, all variables are automatically destroyed only when the window page is closed. Therefore, we usually try to use local variables to reduce global variables and reduce environmental pollution.

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.