ECMAScript 6 notes (let,const, variable's deconstruction assignment)

Source: Internet
Author: User

Refer to Nanyi's book ECMAScript 6 primer, thanks Nandashin!

Let and const command let command

ES6 has a new let command to declare variables. Its usage is similar to Var, but the declared variable is valid only within the code block where the Let command resides.

    • Basic usage
var a = [];for (var010; i++) {  function () {    console.log(i);  };}a[6// 10
var a = [];for (let010; i++) {  function () {    console.log(i);  };}a[6// 6

The variable i is a let declaration, the current I is only valid in this round cycle, so each cycle of I is actually a new variable, so the last output is 6.

    • There is no variable promotion

    • Temporary Dead Zone

As long as a let command exists within a block-level scope, the variable it declares is "bound" to the area and is no longer affected by the external.

    • Duplicate declarations are not allowed

    • Defining block-level scopes

Const command

A const is also used to declare a variable, but a constant is declared. Once declared, the value of the constant cannot be changed.

The constants declared by the const command are also not promoted, and there are also temporary dead zones that can only be used after the declared location.

For a variable of a composite type (reference type), the variable name does not point to the data, but instead points to the address where the data resides. The const command simply guarantees that the variable name points to the same address, and does not guarantee that the address's data will not change, so declaring an object as a constant must be very careful.

Cross-module constants
//const声明的常量只在当前代码块有效。如果想设置跨模块的常量,可以采用下面的写法。// constants.js 模块const1const3const4;// test1.js 模块‘./constants‘// 1// 3// test2.js 模块‘./constants‘// 1// 3
The deconstruction assignment of the variable's deconstruction assignment (destructuring) array

The deconstruction assignment allows you to specify a default value.

vartrue// true‘b‘] = [‘a‘// x=‘a‘, y=‘b‘‘b‘] = [‘a‘undefined// x=‘a‘, y=‘b‘

The ES6 internally uses the strict equality operator (= = =) To determine whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect.

var1] = [undefined// 1var1] = [null// null
Deconstruction assignment of an object

There is an important difference between an object's deconstruction and an array. The elements of the array are arranged in order, the value of the variable is determined by its position, and the object's property has no order, and the variable must have the same name as the property in order to get the correct value.

//如果变量名与属性名不一致,必须写成下面这样var"aaa""bbb"// "aaa"let‘hello‘‘world‘ };let// ‘hello‘// ‘world‘//对象的解构赋值是下面形式的简写var"aaa""bbb" };

The internal mechanism of an object's deconstruction assignment is to find a property of the same name before assigning it to the corresponding variable. The real assignment is the latter, not the former.

varfoofoo"aaa"bar"bbb"//"aaa"//errorisnot defined
Deconstruction assignment of a string

Strings can also be deconstructed for assignment. This is because the string is now converted to an array-like object.

const‘hello‘// "h"// "e"// "l"// "l"// "o"

An array-like object has a length property, so you can also refactor the property to assign a value.

let‘hello‘// 5
Deconstruction assignment of numeric and Boolean values
let123Number// truelettrueBoolean// true

In the above code, both the value and the Boolean wrapper object have the ToString property, so the variable s can fetch the value.
The rule to deconstruct an assignment is to convert it to an object, as long as the value to the right of the equals sign is not an object. Since undefined and null cannot be converted to objects, they will be given an error when they are deconstructed and assigned.

The rule to deconstruct an assignment is to convert it to an object, as long as the value to the right of the equals sign is not an object. Since undefined and null cannot be converted to objects, they will be given an error when they are deconstructed and assigned.

letundefined// TypeErrorletnull// TypeError
The deconstruction assignment of function parameters
[[1,2], [3,4]].map ([A, b] = + A + b)//[3, 7]The default value can also be used for deconstruction of//function parameters.  function move({x = 0, y = 0} = {}) {  return[x, y];} Move ({x:3Y:8});//[3, 8]Move ({x:3});//[3, 0]Move ({});//[0, 0]Move ();//[0, 0][1,undefined,3].map ((x =' yes ') = x)//[1, ' Yes ', 3]
Parentheses problem

Although it is convenient to deconstruct the assignment, it is not easy to parse. For the compiler, whether a formula is a pattern or an expression, there is no way to know from the beginning that the equals sign must be resolved (or not resolved).

    • Cases in which parentheses cannot be used

(1) In a variable declaration statement, you cannot have parentheses.

// 全部报错var [(a)] = [1];var {x: (c)} = {};var ({x: c}) = {};var {(x: c)} = {};var {(x): c} = {};}var2 } };

(2) In function parameters, the pattern cannot have parentheses.

(3) In an assignment statement, you cannot put an entire pattern, or a layer of nested patterns, in parentheses.

    • Cases in which parentheses can be used

There is only one case where parentheses can be used: the non-modal portion of an assignment statement, which can be used in parentheses.

[(b)] = [3// 正确// 正确[(parseInt.prop)] = [3// 正确

The above three lines of statements can be executed correctly, because first they are assignment statements, not declaration statements, and second their parentheses are not part of the pattern. In the first line of the statement, the pattern is the first member of the array, regardless of the parentheses; in the second line of the statement, the pattern is p, not D; The third line statement is the same as the first line statement.

Value of the Use Exchange variable
[x, y] = [y, x];
Returning multiple values from a function

The function can only return a value, and if you want to return multiple values, you can only return them in an array or object. It is very convenient to take these values out if you have an understanding of the construction assignments.

// 返回一个数组function example() {  return [123];}var [a, b, c] = example();// 返回一个对象function example() {  return {    1,    2  };}var { foo, bar } = example();
Definition of function parameters
// 参数是一组有次序的值function f([x, y, z]) { ... }f([123])// 参数是一组无次序的值function f({x, y, z}) {321})
Extracting JSON data
var jsonData = {  42,  "OK",  data: [8675309]}let { id, status, data: number } = jsonData;console.log(id, status, number)// 42, "OK", [867, 5309]
Default values for function parameters
function (url, {  async = true,  beforeSend = function () {},  true,  function () {},  false,  true,  // ... more config}) {  // ... do stuff};
Traverse the map structure
varnew Map();map.set(‘first‘‘hello‘);map.set(‘second‘‘world‘);for (let [key, value] of map) {  " is " + value);}// first is hello// second is world

If you just want to get the key name, or just want to get the key value, you can write it as follows.

// 获取键名for (let [key] of map) {  // ...}// 获取键值for (let [,value] of map) {  // ...}
Specifying methods for Input modules
constrequire("source-map");

ECMAScript 6 notes (let,const, variable's deconstruction assignment)

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.