ES2015(ES6)

2015 is a golden time for JS development, with ES6 proposed by the committee adding a large number of new features on the basis of ES5. Here are the major updates to ES6

  • Let, const keyword
  • Arrow function
  • Class class
  • Module (import/export)
  • Template syntax
  • Function parameter default value
  • Rest parameters
  • Array/object deconstruction
  • Promise

Let/Const

ES6 adds the let/const keyword to solve problems that were previously function scoped only, such as the following:

{
  let a = 10;
  const b = 10;
  var c = 20;
  a = 20;
  b = 30; // Assignment to constant variable
}
a // a is not defined
c / / 20
Copy the code

Arrow function

In ES5, we need to define functions as follows

function sum(value1, value2) {
  return value1 + value2
}
Copy the code

But much less code can be written in the arrow function, as follows:

const sum = (value1, value2) = > {
  return value1 + value2;
}
Copy the code

Class class

In ES5, we defined a class as a stereotype. In ES6, we can declare a class as a class. Here’s how ES5 creates constructors

function Calcutor(moneyBeforeDiscount) {
  this.moneyBeforeDiscount = moneyBeforeDiscount;
}

Calcutor.prototype.moneyAfterDiscount = function (discountRate) {
  return this.moneyBeforeDiscount * (100-discountRate)/100;
}
const demo = new Calcutor(5000)
console.log(demo.moneyAfterDiscount()); / / 4000
Copy the code

Here’s how ES6 creates classes

class Calculator{
    constructor(moneyBeforeDiscount){
        this.moneyBeforeDiscount = moneyBeforeDiscount;
    }
    moneyAfterDiscount(discountRate){
        return this.moneyBeforeDiscount * (100-discountRate)/100; }}const demo = new Calculator(5000);
console.log(demo.moneyAfterDiscount()); / / 4000
Copy the code

Module (import/export)

Before ES6, JS had no native module management. In ES6, we export functions and and variables in a file and then import them in another file. As follows:

// calculator.js
const add = (a, b) = > a +b
const multiply = (a, b) = > a + b

export {add, multiply}

// App.js
import { add } from './calculator'

console.log(add(2.3))
Copy the code

Template syntax

Prior to ES6, if we wanted to concatenate strings and variables, we needed to write them in the following way

const count = 3;
const str = 'count: ' + count;
Copy the code

This approach can be tedious, so ES6 introduces template strings to solve this problem

const count = 3;
const str = `count: ${count}`
Copy the code

You can also write some simple logic in ${} like this:

const count = 3;
const str = `count: ${count + 2}`
Copy the code

Function parameter default value

Before ES6, you could not specify the default values of function arguments directly. You could only use workarounds:

function log(x, y) {
  if (typeof y === 'undefined') {
    y = 'World';
  }
  console.log(x, y)
})
Copy the code

ES6 allows you to set default values for function arguments, which are written directly after the parameter definition

function log(x, y = 'world') {
  console.log(x, y)
}
Copy the code

Rest parameters

ES6 introduced rest arguments to get extra arguments to functions so you don’t need to use arguments objects. This is the pre-ES6 way to get extra parameters

function getParams() {
  return Array.prototype.slice.call(arguments)}Copy the code

Use ES6 syntax

function getParams(. params) {
  return params;
}
Copy the code

Array and object deconstruction extension

Object and array deconstruction is usually used to retrieve a property value from an array or object. Let /const is followed by a list of variables wrapped in brackets []. The values of the variables are the values of the array elements at their positions, as follows:

const [a, b] = [1.2]
console.log(a, b) / / 1. 2
Copy the code

Object deconstruction is to find the corresponding attribute value of the object and assign the value to the variable, as follows:

const {x, y} = {x: 1.y: 2}
console.log(x, y) / / 1. 2
Copy the code

Promise

Promise is usually used to handle things like HTTP requests or programs that consume a lot of time. A Promise can pass the result to the THEN function, which returns a Promise and calls then to process the result. If an error is thrown, a catch can be used to catch it

fetch('/')
  .then(response= > response.json())
  .then(result= > {
    console.log(result)
  })
Copy the code

ES2016(ES7)

ES7 mainly extends ES6 with some array methods such as. Includes () and the index operator **

Array.includes()

const number = [1.2.3]
console.log(number.includes(1)); // true
console.log(number.includes(7)); //false
Copy the code

Exponential operator

console.log(2支那3)
Copy the code

ES2017(ES8)

ES8 added the keyword async/await to make processing asynchronous programs easier. We can use it to avoid spaghetti code and improve the readability of asynchronous code. Here’s how ES6 async works

fetch('/')
  .then(response= > {
    response.json()
  })
  .then(result= > {
    console.log(result)
  })
Copy the code

With ES8, add async keyword to the function first, and then add await before the asynchronous code. The asynchronous code will block the whole JS thread, and only after the asynchronous code returns the result, js will continue to execute. The above code can be changed to the following form

async function fn() {
  const response = await fetch('/');
  const result = await response.json();
  console.log(result);
}
Copy the code

ES2018(ES9)

ES9 adds nothing new, but enhancements to REST and extension operators.

Rest operator.

We use REST on object properties. He simplifies the process of extracting one attribute from an object and assigning the rest to another object, as follows:

const options = {
  enabled: true.text: 'Hello'.color: 'red'
}
const{enabled, ... others} = options;console.log(enabled) // true
console.log(others) // { text: 'Hello', color: 'red' }
Copy the code

Object extension character

Append the extension operator to the object… , and assigns a shallow copy of the current object’s property value to the new object

const options = {
  text: 'Hello'
}
const param = {enabled: true. options}console.log(param) // {enabled: true, text: 'Hello', }
Copy the code

ES2019(ES10)

ES10 makes it much easier to use try/catch without declaring an Error and then catching it. Here’s what happened before. Catch takes an error argument

// before
try {
  fetch('/')}catch (error) {
  console.log(error)
}
Copy the code

Then the error in the catch is optional, which might be helpful in situations where you don’t need to know what the error was thrown, right

try {
  fetch('/')}catch {
  // Handle your logic
}
Copy the code

ES2020(ES11)

Some new features are added to ES11

  • Dynamic introduction
  • BigInt
  • Null-value merge operator
  • Optional chain

Dynamic introduction

In ES6, when importing resources, we use import at the beginning of the file, which is a static import method. The problem solved by dynamic introduction is that there may be too many resources and too large package volume. Some resources can be dynamically introduced to reduce the package volume, as follows:

let stageId = 'A'
let stage

if (stageId === 'A') {
  stage = await import('./stages/A')}else {
  stage = await import('./stages/B')
}

stage.run();
Copy the code

BigInt

In Js, the Number type can only safely represent values from -(2^53-1) to 2^53-1, that is, number. MIN_SAFE_INTEGER to number. MAX_SAFE_INTEGER. You can create a BigInt in one of two ways:

const big = 12344n

const alsoBig = BigInt(20)
Copy the code

Controls the merge operator

When fetching a variable value, it is usually necessary to provide a default value to avoid null or undefined. At present, in JavaScript express the intention of a typical method is to use the | | operator

const score = null;
console.log(score || 'no-score') // no-score
Copy the code

This works for the common case of null or undefined, but there are many variables that are not null or undefined, but take a default value like this:

const score = 0;
console.log(score || 'no-score') // no-score
Copy the code

In this case, the printed result is still no-score. Using ES11, we can avoid undefined or null but the Boolean value is false as follows:

const score = 0;
console.log(score ?? 'no-score') / / 0
Copy the code

Optional chain

If you have the following object, the nesting of attributes is very deep

const student ={
        profile: {school: {name:'RUPP'}}}Copy the code

When we need to get the name attribute is usually need to the following student writing. The format of profile. School. The name, but if the student profile properties does not exist, then sell the following error:

Uncaught TypeError: Cannot read property 'school' of undefined
Copy the code

So to avoid this situation, we can use the if condition to determine whether the student’s profile attribute exists, and if so, we will continue to access the internal attributes

if (student.profile && student.profile.school) {
  return student.profile.school.name
}
Copy the code

But this is too long, and you need to check if the object has a property. That’s how it works, right? . Syntax to determine whether an object has this attribute.

returnstudent? .profile? .school.nameCopy the code

This avoids the possibility of an error when accessing object properties

Welcome to pay attention to “front-end learn well”, front-end learning do not get lost or add wechat SSDWBObo, exchange and learn together