ES6, ES7, ES8 Features One Pot Stew (ES6, ES7, ES8 study Guide) Take study notes here

ES6 new features

  • Let the const
  • Arrow function
  • class
  • modular
  • Template string
  • Deconstruction assignment
  • Extension operator
  • Promise
  • Default values for function arguments
  • Shorthand for object property

1. Let and const

Previously, JS did not have a block-level scope. Const and let fill this convenient gap. Const and let are block-level scopes

Variables defined using var are at function level scope:

{
  var a = 10;
}

console.log(a); / / output 10
Copy the code

Variables defined with let and const are block-level scoped:

{
  let a = 10;
}

console.log(a); //-1 or Error "ReferenceError: a is not defined"
Copy the code

2. Arrow function

See the JavaScript series — common functions, arrow functions, constructor differences and their corresponding this pointing

3. Class

For developers familiar with Java, Object-C, C # and other pure object-oriented languages, class will have a special feeling. ES6 introduced classes to make object-oriented programming in JavaScript much simpler and easier to understand

class Animal {
    // The constructor that will be called when instantiated, if not specified, will have a default constructor with no arguments.
    constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString is a property on the stereotype object
    toString() {
      console.log('name:' + this.name + ',color:' + this.color); }}var animal = new Animal('dog'.'white');// Instantiate Animal
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
  constructor(action) {
    // Subclasses must specify the super function in constructor, otherwise an error will be reported when creating an instance.
    // Constructor with the default super function will be added if the top consructor is not set.
    super('cat'.'white');
    this.action = action;
  }
  toString() {
    console.log(super.toString()); }}var cat = new Cat('catch')
 cat.toString();

 // the instance cat is an instance of cat and Animal, which is identical to Es5.
 console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true
Copy the code

4. The modular

ES5 does not support native modularity, and modules are added as an important part of ES6. The functions of the module mainly consist of export and import. Each module has its own scope. The calling relationship between modules is to specify the interfaces exposed by the module through export, and to refer to the interfaces provided by other modules through import. Namespaces are also created for modules to prevent naming conflicts for functions.

Export export

ES6 allows you to export multiple variables or functions within a module using export.

Export variables

//test.js
export var name = 'Rainbow'
Copy the code

ES6 supports exporting not only variables but also constants. export const sqrt = Math.sqrt; // Export the constant

ES6 treats a file as a module that exports a variable through export. A module can also output multiple variables simultaneously.

 //test.js
 var name = 'Rainbow';
 var age = '24';
 export {name, age};
Copy the code

The export function

// myModule.js
export function myModule(someArg) {
  return someArg;
}
Copy the code

Import

Once the output of a module is defined, it can be referenced in another module by import.

import {myModule} from 'myModule'; // main.js
import {name,age} from 'test'; // test.js
Copy the code

An import statement can import both default functions and other variables. import defaultMethod, { otherMethod } from ‘xxx.js’;

5. Template characters

ES6 supports template strings, which makes concatenation of strings more concise and intuitive

  • Do not use template strings
var name = 'Your name is ' + first + ' ' + last + '. '
Copy the code
  • Using template strings
var name = `Your name is ${first} ${last}. `
Copy the code

6. Deconstruct assignments

Destruct assignment syntax is an expression in JavaScript that allows you to quickly extract values from an array or object and assign them to a defined variable

Gets the value in the array

  • We get values from the array and assign them to variables in the order that corresponds to the order of objects in the array
var foo = ["one"."two"."three"."four"];

var [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"

// If you want to ignore some values, you can get the values you want as follows
var [first, , , last] = foo;
console.log(first); // "one"
console.log(last); // "four"

// You can also write like this
var a, b; // Declare variables first

[a, b] = [1.2];
console.log(a); / / 1
console.log(b); / / 2
Copy the code
  • Set a default value for the variable
var a, b;

[a=5, b=7] = [1];
console.log(a); / / 1
console.log(b); / / 7
Copy the code
  • Easy to swap values of variables
var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); / / 3
console.log(b); / / 1
Copy the code

Gets the value in the object

const student = {
  name:'Ming'.age:'18'.city:'Shanghai'  
};

const {name,age,city} = student;
console.log(name); // "Ming"
console.log(age); 18 "/ /"
console.log(city); // "Shanghai"
Copy the code

7. Extension operator (…)

The extension operator… Array expressions or strings can be expanded syntactically during function calls/array construction; You can also expand an object expression as a key-value when an object is constructed

grammar

  • A function call
myFunction(... iterableObj);Copy the code
  • An array construct or string
[...iterableObj, '4'.'hello'.6];
Copy the code
  • When an object is constructed, a clone or property copy is performed
letobjClone = { ... obj };Copy the code

Application scenarios

  • Use the stretch operator for function calls (most common: don’t pass them one by one outside the function, just pass them one by one inside the function)
function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1.2.3];

// Do not use the extension operator
console.log(sum.apply(null, numbers));

// Use the extension operator
console.log(sum(... numbers));/ / 6
Copy the code
  • Constructing an array

Push, splice, concat, and other methods can be used to make the elements of an existing array part of a new array without expansion syntax. With the expansion syntax, constructing new arrays becomes simpler and more elegant:

const stuendts = ['Jine'.'Tom']; 
const persons = ['Tony'. stuendts,'Aaron'.'Anna'];
conslog.log(persions)// ["Tony", "Jine", "Tom", "Aaron", "Anna"]
Copy the code
  • Copy an array
var arr = [1.2.3];
var arr2 = [...arr]; // equivalent to arr.slice()
arr2.push(4); 
console.log(arr2)/ / [1, 2, 3, 4]
Copy the code
  • Concatenating arrays
var arr1 = [0.1.2];
var arr2 = [3.4.5];
var arr3 = [...arr1, ...arr2];// Append all elements of arR2 to arR1 and return
/ / is equivalent to
var arr4 = arr1.concat(arr2);
Copy the code

8. Promise

See the JavaScript series — Promise, Generator, async, and await for details

9. Shorthand for object properties

ES6 allows you to set a property of an object without specifying the property name

  • Do not use the ES6
const name='Ming',age='18',city='Shanghai';
        
const student = {
    name:name,
    age:age,
    city:city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"}
Copy the code
  • Use the ES6
const name='Ming',age='18',city='Shanghai';
        
const student = {
    name,
    age,
    city
};
console.log(student);//{name: "Ming", age: "18", city: "Shanghai"}
Copy the code

10. Default values for function arguments

ES6 supports setting default values for functions when they are defined:

function foo(height = 50, color = 'red')
{
    // ...
}
Copy the code
  • Not using ES6 set default values:
function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    / /...
}
Copy the code

This is usually fine, but it becomes problematic when the parameter’s Boolean value is false. For example, we call foo like this:

foo(0."")
Copy the code

Since the Boolean value of 0 is false, the height will be 50. Similarly, the value of color is red.

Therefore, function parameter defaults can not only make the code cleaner but also avoid some problems.

ES7 new features

  • The includes() method for arrays
  • Exponential operator

1. Array.prototype.includes()

The includes() function determines whether an array contains a specified value, returning true if it does, and false otherwise.

The includes function is similar to indexOf. The following two expressions are equivalent:

arr.includes(x)
arr.indexOf(x) >= 0
Copy the code

Next, we determine whether the number contains an element:

  • What we did before ES7

Use indexOf() to verify the presence of an element in the array, depending on whether the return value is -1:

let arr = ['react'.'angular'.'vue'];

if (arr.indexOf('react')! = = -1)
{
    console.log('the react there');
}
Copy the code
  • Use ES7’s includes() method
let arr = ['react'.'angular'.'vue'];

if (arr.includes('react'))
{
    console.log('the react there');
}
// Use includes() to verify the presence of an element in the array
Copy the code

2. Index operator (2**5 === 32)

In ES7, the exponent operator ** was introduced, ** has the same function as math.pow (..) Equivalent calculation result

  • Do not use the exponential operator
// Use the custom recursive function calculateExponent or math.pow () to calculate the exponent
function calculateExponent(base, exponent)
{
    if (exponent === 1)
    {
        return base;
    }
    else
    {
        return base * calculateExponent(base, exponent - 1); }}console.log(calculateExponent(2.10)); / / output 1024
console.log(Math.pow(2.10)); / / output 1024
Copy the code
  • Use the exponential operator

Use the exponent operator **, just like the +, -, and so on:

console.log(2六四事件10);/ / output 1024
Copy the code

ES8 new features

  • async/await
  • Object.values()
  • Object.entries()
  • Object.getOwnPropertyDescriptors()
  • PadStart, padEnd
  • A comma is allowed at the end of the function argument list

1. async/await

See the JavaScript series — Promise, Generator, async, and await for details

2. Object.values()

Object.values() is a new function similar to object.keys (), but returns all the values of the property of the Object itself, excluding inherited values.

Suppose we want to traverse all the values of the following object obj:

const obj = {a: 1.b: 2.c: 3};
Copy the code
  • Do not use object.values () : ES7
const vals=Object.keys(obj).map(key= >obj[key]);
console.log(vals);/ / [1, 2, 3]
Copy the code
  • Use object.values () : ES8
const values=Object.values(obj1);
console.log(values);/ / [1, 2, 3]
Copy the code

As you can see from the code above, object.values () saves us the step of going through keys and getting values from them

3. Object.entries

The object.entries () function returns an array of key-value pairs for the enumerable properties of a given Object itself.

Next, let’s iterate over the keys and values of all properties of the obj object:

  • Do not use object.entries () :ES7
Object.keys(obj).forEach(key= >{
	console.log('key:'+key+' value:'+obj[key]);
})
//key:a value:1
//key:b value:2
//key:c value:3
Copy the code
  • The use of the Object. Entries () : ES8
for(let [key,value] of Object.entries(obj1)){
	console.log(`key: ${key} value:${value}`)}//key:a value:1
//key:b value:2
//key:c value:3
Copy the code

3. Object.getOwnPropertyDescriptors()

Returns a descriptor for all self properties of an obj object, or an empty object if there are none

const obj2 = {
	name: 'Jine'.get age() { return '18'}};Object.getOwnPropertyDescriptors(obj2)
Copy the code

4. PadStart, padEnd

str.padStart(targetLength,[padString])

  • TargetLength: the targetLength to which the current string is to be filled. If this value is less than the length of the current string, the current string itself is returned.
  • PadString :(optional) padding a string. If the string is so long that the length of the filled string exceeds the target length, only the leftmost part is retained and the rest is truncated. The default value for this parameter is “”
console.log('0.0'.padStart(4.'10')) / / 10.0
console.log('0.0'.padStart(20))     / / 0.00
Copy the code

str.padEnd(targetLength,[padString])

  • TargetLength: the targetLength to which the current string is to be filled. If this value is less than the length of the current string, the current string itself is returned.
  • PadString :(optional) padding a string. If the string is so long that the length of the filled string exceeds the target length, only the leftmost part is retained and the rest is truncated. The default value for this parameter is “”
console.log('0.0'.padEnd(4.'0'))  / / 0.00
console.log('0.0'.padEnd(10.'0')) / / 0.00000000
Copy the code