Block-level scope of ES6

Source: Internet
Author: User
Tags variable scope

First, preface

Before ECMASCRIPT6 (hereinafter referred to as ES6), there are only two scopes for ECMAScript:

 1, the global scope;

  2, function scope.

Because of these two scopes, there is a term in JavaScript-"variable lift (hoisting)".

As follows:

function func () {    console.log (test);     var test = 1;}; Func ();

Execute the above code in the node environment with the result:

The reason for ' undefined ' is ' variable elevation ', when entering the Func function, all variables declared through Var are placed before and given the value of undefined.

but, The advent of ES6 provides us with a ' block-level scope '. and ' Block-level scope ' does not affect variables declared by var.

What? ' Block-level scope ' does not affect VAR declared variables?!!

Yes, Var declares that the variable has the same nature as the original and has a ' variable boost ' feature. The ' Block-level scope ' is represented by a new command let and a const.

Below, we work with the new let and const commands to get a sense of the block-level scope of the ES6.

Note: because let and const belong to ES6, strict mode must be used, otherwise an error will be given.

As follows:

Let test;

In the node environment, execute the code:

Second, let command

What is a let?

Let is the same as Var, which is used to declare variables. The difference is:

 1 . Let declared variables are only valid at the block level at which they are located;

  2, let does not have the ' variable promotion ' characteristic, but is ' the temporary Dead Zone (temporal dead zone) ' characteristic.

The following will be explained.

1 , let declared variables are only valid at the block level.

As follows:

' Use strict '; function func (args) {    if(true) {        //letdeclares Ilet        i = 6;         // Print I value        console.log (' Inside: ' + i) within if;    }     // Print the I value    again outside of if Console.log (' Outside: ' + i);}; Func ();

Executing the above code in the node environment results in the following:

Through the demo, we can clearly see that the second time (if outside) to print I value, is an error.

This is because the variable I of the Let Declaration is a block-level scope within the IF, not like var.

2 , let There is no ' variable lift ' feature, but a ' temporary Dead zone ' (Temporal dead zone ) ' characteristics.

As follows:

' Use strict '; function func () {    // before let declaration, print i    console.log (i);    let i;}; Func ();

Executing the above code in the node environment results in the following:

Before let declares a variable, the variable is used, and it will be an error rather than a ' variable boost ' as Var.

Actually, let's say that let's have no ' variable promotion ' characteristics, not quite right. Or it is elevated, but ES6 specifies that the variable cannot be used until let declares the variable.

As follows:

' Use strict '; var test = 1; function func () {    // Prints the value of test     console.log (test)    ; = 2;}; Func ();

Executing the above code in the node environment results in the following:

If the let declared variable does not have a variable promotion, the ' 1 ' (test outside the Func function) should be printed, but he has an error stating that it is promoted, only that it cannot be used before its declaration. We call this characteristic "temporary Dead zone" (temporal dead Zone). This feature is only valid for commands that follow the ' block-level scope ' (Let, const).

About let, and finally through a classic case, experience.

As follows:

var arr = [];  for (var i = 0; i < 2; i++) {    function() {        console.log (i);    };}; arr[1] ();

ARR[1] () outputs 2 because the variable declared by VAR will be variable-promoted, and when the arr[1] function is executed, I is taken from the parent function I, and at this point I has become 2, so it will print 2.

The usual practice is to take advantage of the closure feature. As follows:

var arr = [];  for (var i = 0; i < 2; i++) {    = (function(i) {        returnfunction
    () {            console.log (i);        };    } (i));}; arr[1] ();

or attribute mode:

var arr = [];  for (var i = 0; i < 2; i++) {    function self () {        console.log (self.x);     = i;}; arr[1] ();

Now with let, it declares that the variable scope is block-level, so we can also take the same effect with a let.

As follows:

' Use strict '; var arr = [];  for (Let i = 0; i < 2; i++) {    function() {        console.log (i);    };}; arr[1] ();

In the node environment, executing the above code results in the following:

Third, the const command

The const command, like the Let command, declares a variable whose scope is block-level.

So the const follows a rule with a let difference, except that the const is used to declare a constant variable.

Also, declare a constant variable with const, declare it must be assigned at the same time, otherwise you will get an error.

As follows:

' Use strict '; function func () {    const PI;     = 3.14;    Console.log (PI);}; Func ();

In the node environment, executing the above code results in the following:

The right way to do this is to assign a value to the declaration.

Such as:

Const PI = 3.14

Block-level scope of ES6

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.