Deep understanding of JavaScript Scope Series fourth-block scope

Source: Internet
Author: User

xCatalog [1]let [2]const] [3]try front words

Although the function scope is the most common scope unit and the most common design method for most of the current JavaScript, other types of scope cells exist, and even more excellent, concise code, such as block scopes, can be implemented by using other types of scope cells. With the popularization of ES6, the block scope will be used more and more widely. This article is an in-depth understanding of the JavaScript Scope series fourth-block scope

Let
 for (var i= 0; i<10; i++) {    console.log (i);}

The above is a familiar loop code, usually because I only want to use the variable I in the context inside the for loop, but I can actually access it in the global scope, contaminating the entire scope

 for (var i= 0; i<10; i++) {     console.log (i);} Console.log (i); // Ten

ES6 changed the status quo by introducing the new let keyword, which provides a different way of declaring variables other than var. The Let keyword binds a variable to any scope in which it resides (usually {...} Internal), implement block scope

{  = 1;  }; Console.log (i); // referenceerror:i is not defined

Block-level scopes can actually replace the immediate execution of anonymous functions (Iife)

(function() {  = 1;  }) (); Console.log (i); // referenceerror:i is not defined

If you declare the variable I in the code at the beginning of the for loop with let, the scope pollution problem will be avoided

 for (Let i= 0; i<10; i++) {     console.log (i);} Console.log (i); // //referenceerror:i is not defined

The Let of the For loop header not only binds I to the block for the For loop, but in fact it rebind it to each iteration of the loop, ensuring that the value is re-assigned at the end of the previous loop iteration

// equivalent to the previous section of code {let    j;      for (j=0; j<10; j + +        ) {// each iteration rebind         console.log (i);}    }

Cycle

In the following code, because the closure can only get the last value of any variable in the containing function, the console outputs 5 instead of 0

var a = [];  for (var i = 0; i < 5; i++) {    function() {        return  i;    }} Console.log (a[0] ()); // 5

Of course, the value of each loop can be saved by means of a function parameter.

var a = [];  for (var i = 0; i < 5; i++) {    = (function(j) {        returnfunction
    () {            return  J;        }    }) (i);} Console.log (a[0] ()); // 0

It is more convenient to use let, because the Allow loop has a re-assignment process, which is equivalent to preserving the value of each cycle

var a = [];  for (Let i = 0; i < 5; i++) {    function() {        return  i;    }} Console.log (a[0] ()); // 0

Duplicate declaration

Let does not allow repeated declaration of the same variable within the same scope

{  = ten;   var a = 1; // syntaxerror:unexpected identifier}
{  = ten;   = 1; // syntaxerror:unexpected identifier}

Improve

Claims made with let are not promoted in block scope

{  console.log (i); // referenceerror:i is not defined  Let i = 1;  };

Const

In addition to let, ES6 also introduces a const, which can also be used to create a block scope variable, but its value is fixed (constant). Any subsequent attempt to modify the value will cause an error

if (true) {    var a = 2;     = 3;      = 3;      = 4; // typeerror:assignment to constant variable  //  3//  referenceerror:b is not defined

Const-declared constants, as well as non-repeating declarations

Const MESSAGE = "goodbye!"  = "goodbye!"; // syntaxerror:identifier ' message ' has already been declared

Try

A common use of the Try-catch statement is to create a block-level scope in which the declared variable is valid only within the catch

{    = 2;     // 2  //referenceerror:a is not defined

In an environment prior to ES6, you can use the Try-catch statement to achieve a similar effect on the above code

 try  {  2;}  catch   (a) {Console.log (a);  //  2  }console.log (a);  // REFERENCEERROR:A is not defined 
// or Try {    throw  undefined;} Catch (a) {    = 2;     // 2  //referenceerror:a is not defined

Deep understanding of JavaScript Scope Series fourth-block scope

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.