Purpose of adding block-level scopes in ES6

Source: Internet
Author: User

There were only two types of function scope and global scope, which resulted in many inconvenient places:

1) For loop problem: When looking at JS elevation, tangled in the seventh chapter for a long time, is an example of such

function Createfunctions () {    var result = new Array ();    for (var i = 0; i <; i + +) {      Result[i] = function () {         return i;      }      }    return result;}

Regardless of the number of I in this code output RESULT[I] (), the result is 10, which is a disadvantage of no block-level scope. Because the variable i is a global variable, each loop operates on the same I variable, resulting in overwriting, so the result is output 10 regardless of which function in the result array is executed;

2) coverage of internal and external variables

var a = 10;function f () {  console.log (a);  var a = 20;}

The result of the execution is undefined, because the inner variable A is covered with the same name as the outer layer, and the above code is promoted by the Declaration, which is equivalent to the following:

var a = 10;function f () {  var A;  Console.log (a);  A = 20;}

Due to the existence of the inner function scope, the newly declared a is undefined and will be output.

Considering the above two problems, the block-level scope is added, for example, the Var i in the For loop is changed to let I, the expected result will be output, and the second example involves a let and block-level scope binding, there is a temporary dead-zone problem, if only the inner-layer Var is replaced with Let, A referenceerror error occurs where the let declaration is different from Var and is not available before the declaration, so there is an error. If you are interested, you can check it yourself.

Purpose of adding block-level scopes in 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.