When we first started using VUE or React, most of the time we added ES6 to our technology stack. But with so many features in ES6, do we need to master them all? I’m gonna stick to the 80/20 rule and get the usual, useful ones that will get us off the ground fast.

Let’s talk about some of the cute new ES6 features.

1. Declare const and let variables

We all know that before ES6, the var keyword declared variables. Wherever the declaration is, it is considered to be at the top of the function (if it is not in the function, it is at the top of the global scope). This is called function variable promotion. For example:

  function aa() {
    if(bool) {
        var test = 'hello man'
    } else {
        console.log(test)
    }
  }Copy the code

The above code is actually:

  function aa() {
    var test // The variable is promoted
    if(bool) {
        test = 'hello man'
    } else {
        // The value of test is undefined
        console.log(test)
    }
    // The value of test is undefined
  }Copy the code

So you don’t care if bool is true or false. In fact, the test declaration will be created anyway.

Next comes the ES6 hero: We usually declare let for variables and const for constants. Let and const are both block-level scopes. What do you make of this block-level scope?

  • Inside a function
  • Inside a code block

Specifically, the code block inside the {} braces is the scope of let and const.

Look at the following code:

  function aa() {
    if(bool) {
       let test = 'hello man'
    } else {
        //test cannot be accessed here
        console.log(test)
    }
  }Copy the code

Let is scoped in the current code block it is in, but is not promoted to the top of the current function.

Now, const.

    const name = 'lux'
    name = 'joe' // An error will be reported when assigning this parameter againCopy the code

Tell me an interview question

    var funcs = []
    for (var i = 0; i < 10; i++) {
        funcs.push(function() { console.log(i) })
    }
    funcs.forEach(function(func) {
        func()
    })Copy the code

This is a very common interview question, a lot of you know, 10 or 10 times but what if we want to go from 0 to 9? Two solutions. Go straight to the code.

    // ES5 tells us that we can use closures to solve this problem
    var funcs = []
    for (var i = 0; i < 10; i++) {
        func.push((function(value) {
            return function() {
                console.log(value)
            }
        }(i)))
    }
    // es6
    for (let i = 0; i < 10; i++) {
        func.push(function() {
            console.log(i)
        })
    }Copy the code

Achieve the same effect, es6 simple solution is not more let you move!!

2. Template string

Es6 template characters are a boon for developers, addressing the pain points of ES5’s string functionality.

First use, basic string formatting. Concatenate an expression into a string. Delimit with ${}.

    //es5 
    var name = 'lux'
    console.log('hello' + name)
    //es6
    const name = 'lux'
    console.log(`hello ${name}`) //hello luxCopy the code

Second, in ES5 we use a backslash (\) to do multi-line strings or string concatenation. ES6 backquotes (‘ ‘) are fixed.

    // es5
    var msg = "Hi \ man! "
    // es6
    const template = `
       
hello world
`
Copy the code

Es6 of course has a lot of nifty methods for strings as well. Name a few common ones.

    // 1.includes: checks whether it is included and returns a Boolean value directly
    let str = 'hahay'
    console.log(str.includes('y') // true
    // 2.repeat: Get string n times
    let s = 'hh'
    console.log(s.repeat(3)) // 'hehehe'
    Math.floor(num) if you put in decimalsCopy the code

3. The function

Function default arguments

In ES5 what are the default values of the parameters we define for functions?

    function action(num) {
        num = num || 200
       // When num is passed in, num is the value passed in
       // When no argument is passed, num has the default value of 200
        return num
    }Copy the code

If num = 200, it will be false. If num = 200, it will be false

ES6 provides default values for parameters. This parameter is initialized when the function is defined, so that it can be used if the parameter is not passed in.

    function action(num = 200) { console.log(num) }
    action(a) / / 200
    action(300). / / 300Copy the code

Arrow function

The interesting part of ES6 is the shortcuts to functions. That’s the arrow function.

The three most intuitive features of the arrow function.

  • You do not need the function keyword to create functions
  • Omit the return keyword
  • Inherits the this keyword from the current context
/ / such as:
    [1.2.3].map( x => x + 1 )

// Equivalent to:
    [1.2.3].map((function(x){
        return x + 1
    }).bind(this))Copy the code

One small detail.

You can omit the parentheses when your function has only one argument. You can omit {} when a function returns only one expression; Such as:

    var people = name= >'hello' + name
    // The name argument has no parenthesesCopy the code

As a reference

    var people = (name, age) = > {
        const fullName = 'h' + name
        return fullName
    } 
    // An error is reported if () or {} is missingCopy the code

4. Extended object functionality

Short for object initialization

ES5 We write objects in the form of key-value pairs. It is possible for value pairs to have the same name. Such as:

    function people(name, age) {
        return {
            name: name,
            age: age
        };
    }Copy the code

Key value pairs have the same name, ES6 can be abbreviated as:

    function people(name, age) {
        return {
            name,
            age
        };
    }Copy the code

ES6 also improves the syntax for assigning values to object literal methods. ES5 adds methods for objects:

    const people = {
        name: 'lux'.getName: function() {
            console.log(this.name)
        }
    }Copy the code

ES6 makes this syntax more concise by omitting the colon and function keyword

    const people = {
        name: 'lux',
        getName () {
            console.log(this.name)
        }
    }Copy the code

ES6 objects provide the object.assign () method to implement shallow copy. Object.assign() can copy any number of source objects’ own enumerable attributes to the target Object and return the target Object. The first parameter is the target object. In a real project, in order not to change the source object. It usually passes the target object as {}

    const obj = Object.assign({}, objA, objB)Copy the code

5. Easier data access — deconstruction

Arrays and objects are the most common and important representations in JS. To simplify extracting information, ES6 has added deconstruction, the process of breaking a data structure into smaller parts

In ES5, we extract the information in the object as follows:

    const people = { name: 'lux', age: 20 }
    const name = people.name
    const age = people.age
    console.log(name + The '-' + age)Copy the code

Does that sound familiar? Yes, this is how we get object information before ES6, one by one. Now, deconstruction allows us to take data from an object or an array and store it as a variable, for example

    / / object
    const people = {
        name: 'lux',
        age: 20
    }
    const { name, age } = people
    console.log(`${name} --- ${age}`)
    / / array
    const color = ['red'.'blue']
    const [first, second] = color
    console.log(first) //'red'
    console.log(second) //'blue'Copy the code

6.Spread Operator Expand Operator

Another interesting feature of ES6 is that the Spread Operator is also three dots… I’m going to show you what it does.

Assemble objects or arrays

    / / array
    const color = ['red'.'yellow']
    const colorful = [...color.'green'.'pink']
    console.log(colorful) //[red, yellow, green, pink]

    / / object
    const alp = { fist: 'a'.second: 'b'}
    constalphabets = { ... alp, third:'c' }
    console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"
}Copy the code

Sometimes we want to get an array or an object except for the first few items or other items except for certain items

/ / arrayconst number = [1.2.3.4.5]
    const [first, ...rest] = number
    console.log(rest) //2.3.4.5/ / objectconst user = {
        username: 'lux',
        gender: 'female',
        age: 19,
        address: 'peking'
    }
    const{ username, ... rest } = user console.log(rest) //{"address": "peking"."age": 19."gender": "female"
}Copy the code

For Object, it can also be used to compose new objects. (ES2017 stage-2 proposal) Of course, if there are duplicate attribute names, the right side overwrites the left side

    const first = {
        a: 1.b: 2,
        c: 6,
    }
    const second = {
        c: 3,
        d: 4
    }
    const total = { ...first..second }
    console.log(total) // { a: 1, b: 2, c: 3, d: 4 }Copy the code

7. The import and export

Import Import module, export Export module

// Import all
import people from './example'

There is a special case that allows you to import the entire module as a single object
// All exports of the module will exist as properties of the object
import * as example from "./example.js"
console.log(example.name)
console.log(example.age)
console.log(example.getName())

// Import section
import {name, age} from './example'

// Export defaults with one and only one default
export default App

// Partial export
export class App extend Component {};Copy the code

I’ve been asked before what’s the difference between importing without curly braces. Here’s a summary of my work:

1.When usingexport defaultWhen people is exported, it is usedimportPeople import (without curly braces)2.There can only be one in a fileexport default. But there can be more than oneexport.3.When usingexportName is usedimport{name} import (remember to close curly braces)4.When you have a file, you have oneexport defaultPeople, there's multiple of themexportThe name orexportAge, import is usedimport people, { name, age } 

5.When there are more than n in a fileexportExport many modules, import in addition to one by one, can also be usedimport * as exampleCopy the code

8. Promise

Too many callbacks or nesting of code prior to Promise resulted in poor readability, high coupling, and low scalability. Through the Promise mechanism, the code structure is flat, which greatly improves the code readability. Using synchronous programming to write asynchronous code, save the linear code logic, greatly reduce the code coupling and improve the scalability of the program.

In plain English, write asynchronous code in a synchronous manner.

Making an asynchronous request

    fetch('/api/todos')
      .then(res= > res.json())
      .then(data= > ({ data }))
      .catch(err= > ({ err }));Copy the code

Today I read an interesting article about the interview questions.

    setTimeout(function() {
      console.log(1)},0);
    new Promise(function executor(resolve) {
      console.log(2);
      for( var i=0 ; i<10000 ; i++ ) {
        i == 9999 && resolve();
      }
      console.log(3);
    }).then(function() {
      console.log(4);
    });
    console.log(5);Copy the code

Excuse me? This front-end interview is screwing up!

Of course, this is just the tip of the iceberg. You need to learn more about applications.

9.Generators

A generator is a function that returns an iterator. A generator function is also a function, most intuitively represented by an asterisk *, that uses the yield keyword in its body. Interestingly, the function pauses at each yield.

Here is a vivid example of life. When we go to the bank, we have to get a queue number from the machine in the lobby. You get your queue number, and the machine doesn’t automatically issue another ticket for you. This means that the machine “stops” and does not continue to spit out tickets until the next person is aroused again.

OK. Talk about iterators. When you call a generator, it returns an iterator object. This iterator object has a method called next to help you restart the generator and get the next value. The next method not only returns a value, it returns an object with two attributes: done and value. Value is the value you get, and done is used to indicate whether your generator has stopped providing values. So let’s continue with the example where we just picked up the ticket, so each line number is value here, and whether the paper that printed the ticket ran out is done here.

    / / generator
    function *createIterator() {
        yield 1;
        yield 2;
        yield 3;
    }

    // Generators can be called like normal functions, but return an iterator
    let iterator = createIterator();

    console.log(iterator.next().value); / / 1
    console.log(iterator.next().value); / / 2
    console.log(iterator.next().value); / / 3Copy the code

So what’s the use of generators and iterators?

Much of the excitement surrounding generators is directly related to asynchronous programming. Asynchronous calls are very difficult for us, our functions don’t wait for an asynchronous call to finish before executing, you might want to use callback functions, (there are other schemes such as promises such as Async/await).

Generators can make our code wait. You don’t need nested callback functions. Using generator ensures that the execution of the function is paused when the asynchronous call completes before our Generator function runs a line of code.

The problem is that you can’t just keep calling next() manually, you need a method that calls the generator and starts the iterator. Something like this

    function run(taskDef) { //taskDef is a generator function

        // Create an iterator and make it available elsewhere
        let task = taskDef();

        // Start the task
        let result = task.next(a);// Recursively uses functions to keep calls to next()
        function step() {

            // If there is more to be done
            if(! result.done) { result =task.next(a);step();
            }
        }

        // Start the process
        step(a); }Copy the code

Perhaps the most interesting and exciting aspect of generators and iterators is the ability to create clean-looking asynchronous operation code. Instead of using callbacks everywhere, you can create code that looks synchronous but actually uses yield to wait for an asynchronous operation to end.

conclusion

ES6 features much more than that, but for our daily development. That’s enough. There are lots of interesting ways. Such as findIndex, every, some… And so on. This includes using set to complete the interview questions frequent-flier array to redo the questions. My friends and I were shocked!