Js global variables and local variables

Source: Internet
Author: User

Js global variables and local variables

This article is a summary of your own learning.

A simple definition of global variables and local variables: all variables declared outside the function are global variables, and those declared in the function are local variables.

 

I. duplicate names of local variables and global variables overwrite global variables.

1 var a = 1;  2 function test1() {  3   var a = 2;  4   alert(a);  5 }  6 test1();// 2  

Here, the function defines a as a local variable. Its scope is between functions {}, and a defined outside the function is a global variable, its scope is the entire program (the description is a bit inaccurate ). In the function, the local variable and the global variable are duplicated. The local variable overwrites the global variable.

 

2. One point that must be explained when we mention global variables and local variables isVariable increase(This is a pitfall ). 'Unlike C/C ++, The JS engine is used to obtain all declared variables and then execute them one by one, all variable declaration statements are promoted to the header of the current code block '. Note: A code block refers to a {} of a function. Normally, the variables in the {} of if, while, and for are not upgraded.

After learning about the variable upgrade, we use the following code to demonstrate it:

1 var a = 1;  2 function test1() {  3     alert(a);  4     var a = 2;  5     alert(a);  6 }  7 test1();   8 alert(a);//undefined  2  1

Why is the result not 1 2 1? The reason is that the Code is upgraded. The Code actually executed is as follows::

 

1 var a = 1; 2 function test1 () {3 var a; // global variables are overwritten when the names of local variables and global variables are duplicated, at this time, only the declaration of a has not defined 4 alert (a); // Therefore, the execution of alert value is undefined 5 a = 2; 6 alert (a); 7} 8 test1 (); 9 alert (a); // undefined 2

 

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.