JS variable scope--variable elevation

Source: Internet
Author: User
Tags variable scope

1.JS Scope

In ES5, JS has only two forms of scope: global scope and function scope, and in ES6, a new block-level scope (the scope of the most recent curly braces) is added, but only the variables declared by the Let way are limited.

2. Variable declaration

1 var x;      // Variable Declaration 2 var x=1;    // variable declaration and assignment 3 x = 1;    // define global variables and assign values

3. Function declaration

function fn () {};     // function declaration and definition var function (){};    // is actually defining a local variable, fn and an anonymous function, and assigning the anonymous function to the FN

4. Variable Promotion

var New Date (); function fn () {    console.log (TMP);   // Wed Jul 22:11:56 gmt+0800 (China Standard Time)}
FN ();

A case

var New Date (); function fn () {    console.log (TMP);     // undefined    if (false) {        var tmp = ' Hello ';    }} fn ();

b Case

var New Date (); function fn () {    console.log (TMP);     // undefined    if (true) {        var tmp = ' Hello ';    }} fn ();

C Case

As can be seen from the above, the B case and the C case are different from the a case, that is, because the variable is promoted (the Ps:c case is different from the B case is the judging condition is true, but this is not to see whether the code is executed, is to see whether the variable is defined). The FN function defines the variable tmp with the same name, which is promoted to the top of the function, regardless of where the TMP variable is defined anywhere in the function. is equivalent to the following scenario:

var New Date (); Console.log (TMP); function fn () {        var  tmp;    Console.log (TMP);     // undefined    if (false) {        var tmp = ' Hello ';    }} fn ();

It is necessary to note that although all declarations (including ES5 Var, function, and ES6 function *, let, const, Class) are promoted, VAR, function, function * and let, const, Class's ascension is not the same! The specific reasons can be seen here (in general, although Let,const,class is also promoted, but it is not initialized, at this time to visit them will be reported Referenceerror exception, they need to be executed when the statement will be initialized, The state before being initialized is called the temporal dead Zone).

For this reason, it is recommended that when declaring variables, the variables used are written at the top of the scope (global scope or function scope), so that the code looks clearer and easier to see that the variable is from the scope of the function and which is from the scope chain.

5. Repeated statements

var x = 1; console.log (x); if (true) {    var x = 2;    Console.log (x);} Console.log (x);

The above output is actually: 1 2 2. Although it appears that the X is declared two times, but it said that JS var variable only global scope and function scope two, and the declaration will be promoted, so in fact, X will be declared at the top of the first place, VAR x=2 declaration will be ignored, only for assignment. This means that the above code is actually consistent with the following:

var x = 1; console.log (x); if (true) {    = 2;    Console.log (x);} Console.log (x);

6, the function and the variable simultaneously raise the question

Console.log (FN); function fn () {}; var fn = ' string ';

The above output is actually: function fn(){}  , that is, the function content.

Console.log (FN); var function fn () {}; var fn = ' string ';

At this point the output is undefined, it is not difficult to understand the above declaration of ascension of the truth.

Summarize:

To thoroughly understand the scope and hoisting of JS, just remember the following three points:

1. All declarations will be promoted to the top of the scope

2, the same variable declaration is only made once, and therefore other declarations will be ignored

3, the function declaration priority is superior to the variable declaration, and the function declaration will be promoted together with the definition

Attention:

With the WITH statement, you can temporarily change the scope chain of a run-time context, where a variable defined by a non-VAR is accessed, and the property of the object in with is accessed first, and then the property is checked upward along the scope chain.

JS variable scope--variable elevation

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.