JavaScript series article: Talk about let and const

Source: Internet
Author: User

Recently exposed to some of the new features of ES6, you want to borrow let and const two commands to talk about JavaScript improvements in terms of variables.

Since let and const have a lot of similarities, we'll start by saying let.

1. Let adds a block-level scope

We know that JavaScript is not block scoped, and if you use VAR to declare a variable inside a block, it is still visible outside the block of code:

if (true) {     var foo = 3;} Console.log (foo);    3for (var i = 0; i < 9; i++) {     var j = i;} Console.log (i);      9console.log (j);      8

As you can see, in the above code, although we declare variables within a block, after the code block has been executed, we can still access the corresponding variables, indicating that there is no block-level scope in JavaScript.

The ES6 specification brings a block-level scope to the developer, and if Var is replaced with a let command, we can get a block-level variable:

if (true) {let     foo = 3;} Console.log (foo);   Uncaught referenceerrorfor (Let i = 0; i < 9; i++) {let     j = i;} Console.log (i);     Uncaught ReferenceErrorconsole.log (j);     Uncaught Referenceerror

As can be seen from the above code, the variables declared within the block are not visible outside the block, and an exception is thrown if you attempt to reference a variable within a block that is declared with Let.

2. Let constrains the variable promotion

In JavaScript, variable elevation is common, such as the following code:

function hoistvariable () {    console.log (' foo: ', foo);//foo:undefined    var foo = 3;} Hoistvariable ();

Before the code is formally executed, the compiler will pre-compile the parsing phase of the code, at which time the variables and functions in the current scope are promoted to the top of the scope. (Note: Most of the current JavaScript engines compile the source code, and precompilation and promotion are abstractions.) )

The code logic after precompilation is as follows:

function hoistvariable () {    var foo;    Console.log (' foo: ', foo); foo:undefined    foo = 3;} Hoistvariable ();

The Let command in ES6 regulates the declaration of variables, constrains the variable promotion, that is, we must declare before we can use, the following segment code will be error:

function Nonhoistingfunc () {    console.log (' foo: ', foo);//uncaught referenceerror let    foo = 3;} Nonhoistingfunc ();

The correct way to use it is to always place the variable declaration at the top of the current scope:

function Nonhoistingfunc () {let    foo = 3;    Console.log (' foo: ', foo); 3}nonhoistingfunc ();

It is important to note that, regardless of whether it is Var or let, there has been a variable promotion during the precompilation process, but unlike Var, the ES6 has constrained let, which stipulates that access to allow variables is not allowed in any way until a true lexical variable is declared . So from the developer's point of view, let forbids the behavior of variable promotion.

For this, you can refer to "Let and const variable declarations" in the ES6 specification.

3. Let has a temporary dead zone

As long as the Let command exists within the block, the variable is bound to the current block scope and is no longer affected by the external variable, and the following code throws an error:

var foo = 3;if (true) {    foo = 5;//uncaught referenceerror let    foo;}

ES6 rules if a let command exists within a block, the block becomes a closed scope and requires the let variable to be declared before it can be used, and it does not refer to an external variable if it is used before the declaration.

If you replace the Let to Var, because there is no block-level scope, the declaration of the variable is actually repeated with the first line, which is equivalent to the following code:

var foo;foo= 3;if (True) {    foo = 5;}
4. Let disallow duplicate declaration variables

As mentioned above, variables can be declared repeatedly using VAR, but let does not allow repeated declarations of the same variable within the same scope, and the following code throws an error:

Syntaxerrorfunction func () {let    foo = 3;    var foo = 5;} Syntaxerrorfunction func () {let    foo = 3;    let foo = 5;} syntaxerrorfunction func (ARG) {let    arg;}
5. Let does not become a property of a global object

When we declare a variable using var globally, this variable automatically becomes the property of the global object (the Global object is window and global, respectively, in the browser and node. JS environment, but let is a standalone variable that does not become a property of the global object:

var a = 3;console.log (WINDOW.A); 3let B = 5;console.log (WINDOW.B); Undefined
6. Last: const command

The rules described above are applicable to the Const command, but thevariable declared by const cannot be re-assigned , and because of this rule, theconst variable declaration must be initialized and cannot be assigned later, so the following code is not valid:

Const A = 3;a = 5;   Uncaught typeerror:assignment to constant Variableconst b; Uncaught syntaxerror:missing initializer in const declaration

The above is the content of let and const, we can see that let and const greatly improved the ES5 variable mechanism, so that JS more rigorous and normative, with the increase of ES6 support, we should start to get used to the use of and Const.

Resources:

http://es6.ruanyifeng.com/#docs/let

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Http://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-not-hoisted-in-es6

JavaScript series article: Talk about let and const

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.