es6 new syntax

What is ES6

ECMAScript, the abbreviation of ECMAScript, is the standard of JavaScript language officially released in June 2015, officially named ECMAScript 2015 (ES2015). Its goal is to make JavaScript language can be used to write complex large-scale applications and become an enterprise development language.

In some cases, ES6 also refers to the new features of ES2015 and later, even if later versions should be called ES7, ES8, etc.

Why ES6
The birth of each standard means the improvement of the language and the enhancement of its functions. There are some unsatisfying aspects in JavaScript language itself.

  • Variable promotion increases the unpredictability of program runtime
  • The grammar is too loose to realize the same function. Different people may write different codes

ES6 new syntax

let

New keywords for declaring variables in ES6
Variables declared with let have no scope escalation.

 console.log(num);
    let num = 10;

Uncaught ReferenceError: Cannot access 'num' before initialization
at
This code will report an error. If it is declared by var, it will show that the value of num is undefined.

let declared variables have block level scope

 if (true) {
      let a = 1;
    }
    console.log(let);

The result is: Uncaught ReferenceError: let is not defined
at
Variables declared within a code block cannot be accessed outside the code.

Use let in loop

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

First, when i declared with var is executed at the end, 3 is printed, which shows that i in the for loop is actually a global variable. When a function executes, the i accessed is the i of the global variable.

If it's let

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

Even if the value of the global variable i is changed outside, there is already a block level scope variable i inside the for loop. Each loop will declare a variable i within the currently executed code block, and the function will print the i in the current scope.

Using let will cause temporary deadband

 var num = 40;
    if (true){
      console.log(num);
      let num = 10;
    }

The result of this code is: Uncaught ReferenceError: Cannot access' num 'before initialization
at
As long as there are variables declared with let in the current scope, variables with the same name at the upper level cannot be accessed. If the declaration is after access, an error will be reported.

summary

  • let keyword is used to declare variables
  • Variables declared using the let keyword have block level scope
  • In a brace, only variables declared with let keyword have block level scope var keyword does not have this feature
  • Prevent loop variables from becoming global variables
  • Variables declared with let keyword have no variable promotion
  • Variables declared with let keyword have temporary deadband property

const

Declare a constant, which is the amount whose value (memory address) cannot be changed
Has block level scope

if (true) {
      const a = 10;
    }
    console.log(a);

The result is: Uncaught ReferenceError: a is not defined
at

Must be assigned when declaring a constant

  const PI ;

Uncaught SyntaxError: Missing initializer in const declaration
Constants are not initialized when they are declared.

Cannot modify after constant declaration

 const PI = 3.1415926 ;
    PI  = 3.14;

Uncaught TypeError: Assignment to constant variable.
a
The constant is assigned a value.

But if it's data of reference type

const arr = [1,2,3,4,56];
    console.log(arr);
    
    arr[0] = 2;
    console.log(arr);

You can change the internal value of the reference type data saved by the constant. The constant detects that the memory address saved by the constant cannot be modified.

summary

  • The variable declared by const is a constant
  • Constant cannot be reassigned. If it is a basic data type, the value cannot be changed. If it is a complex data type, the memory address cannot be modified.
  • A value must be given when const is declared.

The difference among let, const and var

  • The variables defined by var declaration have scope promotion, without the concept of block, can be accessed across blocks, not across functions.
  • The variables defined by let, without scope promotion, can only be accessed in the scope, not across blocks or functions.
  • const is used to define constants, which must be initialized (i.e. must be assigned), and can only be accessed in the block scope

Destructuring assignment

In ES6, it is allowed to extract values from arrays, assign values to variables according to corresponding positions, and the objects can also be deconstructed

Array deconstruction

/Array deconstruction allows us to extract the corresponding values from the array in the corresponding order. If the deconstruction fails to return undefined, an error will be thrown if the calculated result on the right side of the equal sign is null or undefined

let arr = [1,2,3]
 let [a,b,c,d] = arr;
    console.log(a);
    console.log(b);
    console.log(c);
    console.log(d);

Print results:
1
2
3
undefined
Because d did not find the corresponding value in the array.

Destructuring assignment

let arr = [1,2,3]
 let [,,c] = arr;
    console.log(c);//3

Print:
3
You can use the variable that the placeholder will want to assign to correspond to the corresponding value.

Reassignment

let arr = [1,2,3]
 let a = 10;
    let b = 100;
    [a,b] = arr;
    console.log(a);//1
    console.log(b);//2

In this way, you can reassign variables.
Default assignment

let arr = [1,2,3]
 let [a,b,c,d=100] = arr;
    console.log(a);//1
    console.log(b);//2
    console.log(c);//3
    console.log(d);//100

When the variable cannot find the value of the object, it is assigned to the value after the equal sign

Object deconstruction

Destructuring assignment

    let obj = {
      name:'Zhang San',
      age:18,
      phone:{
        number:888
      }
    }
let {name,age} = obj;
    console.log(name);//Zhang San
    console.log(age);18

The variable name matches the key in the object and returns the value after the matching is successful

When the variable name is different from the property in the object

    let Mname = 'Li Si';
    let Mage = 28;
    ({name:Mname,
    age:Mage} = obj);
    console.log(Mname);//Zhang San
    console.log(Mage);//18

Because the let keyword is missing in the deconstruction, we need to add brackets to make the left and right sides form a complete expression.

Deconstruction of deep complex data types

    let {
      phone :{
        number:Mnum
      }
    } = obj;
    console.log(Mnum);//888

This assignment method can also be combined with array deconstruction.

application

    // 1 exchange of variable values
    // let a = 10;
    // let b = 20;
    // [a,b] = [b,a];
    // console.log(a);//20
    // console.log(b);//10

    // 2 function returns multiple values
    // let [a,b,c] = (function () {
    //   return [2,2,4]
    // })();
    // console.log(a);//2
    // console.log(b);//2
    // console.log(c);//4
    // let {name:Mname} = (function () {
    //   return {
    //     name: 'Zhang San'
    //   }
    // })();
    // console.log(Mname); / / Zhang San
   
    // 3 as parameter list
    // function fn([a, b, c]) {
    //   console.log(a,b,c);
    // }
    // fn([1,2,3]);//1 2 3

    // extend
  // function fn2(a,{b,c,d}) {
  //   console.log(a,b,c,d);
    
  // }
  // fn2(1,{b:3,c:4,d:5})// 1 3 4 5

summary

  • Deconstruction assignment is to decompose the data and assign values to variables
  • If the deconstruction is unsuccessful and the number of variables does not match the number of values, the value of the variable is undefined
  • Array deconstruction is enclosed by brackets, multiple variables are separated by commas, object deconstruction is enclosed by braces, and multiple variables are separated by commas
  • By using deconstruction assignment, we can easily get the attributes and methods in the object

Arrow function

New ways to define functions in ES6

    // Arrow functions can only be written as function expressions,
    // () = > {}, = > are necessary symbols and cannot be omitted, () parameter, {} is method body (function body)
    //  1. Arrow function parameters
    // Zero
    var fn1 = () => {
      console.log('Arrow function');
    }
    // One
    var fn2 = num => {
      return num;
    }
    // If the returned content is a very simple code
    // What needs to be returned is a very simple code.
    var fn3 = num => num;
    // console.log(fn3(3));
    //  This in arrow function, not bound to this, this in arrow function will point to the context defined by arrow function
    var fn4 = function () {
      console.log(this);
    }
    var obj = {
      name: 'Zhang San'
    }
  //  No grarguments are undefined in the arrow function
  var fn5 = (name)=>{
    console.log(arguments);
  }
  // fn5('zhang San ')

Extended operators

The extended operator can split the data in the form of an array into sequences in the array, and the data type is consistent with the original array.

    // The extended operator can split the data in the form of an array into sequences in the array, and the data type is consistent with the original array.
    let arr = [1,2,3];
    console.log(...arr);
    console.log.apply(null,arr);

    // Extended merge array
    var arr1 = [1,2,3];
    var arr2 = [3,4,5];
    var arr3 = [...arr1,...arr2];
    console.log(arr3);

    // Convert collection to array
    var NodeLi = document.querySelectorAll('div');
    var HTMLColl = document.getElementsByClassName('box');
    var arr4 = [...NodeLi];
    var arr5 = [...HTMLColl];
    console.log(NodeLi);
    console.log(HTMLColl);
    console.log(arr4);
    console.log(arr5);

Array.from() can convert a pseudo array to an array

    // Array.from()
    // Convert a pseudo array to an array
    let obj = {
      0: 'a',
      1: 'b',
      2: 'c',
      3: 'd',
      'length': 4
    }
    let arr = Array.from(obj);
    let arr1 = Array.from(obj,item=>item+'Z','0')
    console.log(arr);
    console.log(arr1);
    for (const k of obj) {
      console.log(k);
      
    }

Template string

Using the template string, you can easily insert the expression into the string and use ${} as the decomposition.
In es5, the backslash is used to wrap the string, while the template string itself can directly recognize the newline.

Object.is() judge whether two data are completely equal

Object.is() is basically the same as = =, but it is different from the latter in two places

        console.log(-0===+0);//true
        console.log(Object.is(-0,+0));//false
        console.log(NaN===0/0);//false
        console.log(Object.is(NaN,0/0));//true
        var num1 = 0/0 ;//NaN
        var num2 = 1/0 ;//Infinity
        var num3 = 1/0*0;//NaN

Tags: ECMAScript Javascript

Posted on Thu, 04 Jun 2020 09:04:56 -0400 by haaglin