Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The Most Useful Features in The Latest Javascript (Since ES6)

In June 2015, after a six-year hiatus, Javascript received a major update that brought many new features. Since then, we have released a new release every year with a series of new features designed to help developers become more productive. To help you track the progress of the Javascript version, I’ll list the most useful features grouped by version and add some code examples for a better overview.

ES6 (ECMAScript 2015)

Arrow function (=>)

The arrow function is shorthand for function syntax (=>). It brings two major advantages to developers. First, the arrow function helps us avoid using.bind() or other methods to apply this correctly, because arrow functions share the same lexical this with their surroundings. Another benefit of using the arrow function is that our code looks much better; it’s not as verbose as using regular functions.

// traditional function expression
var numbers = [2.6.40];
var twiceNum = numbers.map(function (number) { return number * 2 })

// arrow functional
var numbers = [2.6.40];
var twiceNum = numbers.map((number) = > number * 2);
// lexical this
var greenBtn = documentDocument.getelementbyid (" greenBtn "); GreenButton. AddEventListener (' click ',function () {
    this. The style. The backgroundColor = "red";// no more binding
})
Copy the code

class

Classes can be a very useful feature for the fun of object-oriented programming. They make it super easy to write code based on class patterns. Classes support stereotype inheritance, constructors, super calls, and instances and static methods. Let’s see how easy it is to create classes now:

// Class
class Person {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    sayHi() {
        return'Hi, my name is ${firstName}.Nice to meet you. }}Copy the code

Template string

In the example above, you may have realized that I didn’t use a plus sign to add a variable to the string. ES6 implements a very useful feature called template strings. It allows us to implement variables without aborting the string. It is sufficient to put the variable in curly braces and prefix is with the $sign. It is also important to enclose strings in quotes. It can be very useful when constructing API requests. Let’s take a look at the code:

varName = 'Peter', city = 'London';// Before ES6
var greeting = "Hello, my name is " + name + ". I am from " + city + ".";
// After ES6 
varGreeting = 'Hello, my name is ${name}. I'mfromThe ${city}. 'Copy the code

Let and Const

ES6 implements two new keywords: const and let. They are used to declare variables. Let works much like VAR, but variables have block scope, so it is only available in declared blocks of code. Const is used to declare constants. It works like a let, but requires an assignment to declare const. Let’s take a look at some code examples:

// Let -- variable is available only in the block of code
function calculate(x) {
    var y = 0;
    if (x > 10) {
        // let y is only available in this block of code
        let y = 30;
        return y;
    }
    return y;
}
Copy the code

Promises

The creators of ECMAScript 2015 also provided us with a standardized Promise implementation, which is very useful, whereas asynchronous programming is often used today. We don’t have to worry about a callback to hell anymore. A Promise is always in one of three states: wait, complete, or reject. If a Promise is resolved, you can also use the.then() method to respond, or the.catch() method to check why it was rejected. Let’s take a look at the code:

const checkResult = () = > new Promise(resolve, reject) => {
    setTimeout(resolve, 500)
}
checkResult()
    .then((result) = > { console.log(result); })
    .catch((error) = > { console.log(error); })
Copy the code

ES7 (ECMAScript 2016)

Array.prototype.includes

A new method for arrays appears in ES7. The.includes() method makes it easier to check if there are specific values in an array. Where previously developers using indexOf had to create an extra function to check, we can now use.include(), which will return true if there are specific elements in the array and false if there are none. Let’s look at a code example:

var fruits = ['banana'.'apple'.'grape'.'nut'.'orange'];
var favoriteFruit = 'banana';
// Before ES7
function isFruit(fruit) {
    if(fruits.indexOf(fruit) ! = = -1) {
        return true;
    } else {
        return false;
    }
}
isFruit(favoriteFruit); // returns true
// After ES7
fruits.includes(favoriteFruit); // returns true
Copy the code

Exponentiation computation

This is most important for developers working on more advanced math, 3D, VR, or data visualization. Previously, this could be done through loops, math.pow (), or recursive functions, but now the approach is much simpler. Let’s look at some code:

// Before ES7 (loop case) 
function calculate(num, exponent) {
    var res = 1;
    for (var i = 0; i < exponent; i++) {
        res *= num;
    }
    return res;
}
// After ES7
const calculate = (num, exponent) = > num ** exponent;
Copy the code

ES8 (ECMAScript 2017)

Object. The values () and the Object. Entries ()

The object.values () method implemented in ECMAScript2017 allows us to take all the values of an object and return them as an array. Another useful feature of Object in ES8 is the object.entries () method. It allows us to take all the entries and display them as an array of arrays. Let’s look at some code:

var person = {
    name: Jenny,age: 24.country: 'the UK',city: London,}// Object.values()
var arrJenny = Object.values(person); // returns [' Jenny ', 24, 'UK', 'London'];
// Object.entries()
var arrJennyEntries = Object.entries(person); / / returns the [[' name ', 'Jenny'], [' age, 24], [' country ', 'the UK'], [' city ', 'London']].
Copy the code

String. The prototype. PadEnd () and String. Prototype. PadStart ()

There are also some new strings in ES8. When your string doesn’t have enough length, you can use one of the new methods to add some characters until it reaches the desired length. PadEnd () adds the selected character (default: space) to the end of the string, and padStart() means at the beginning of the string. Let’s see how it works in an example:

varString = "Alice";// padStart() -- assume our string needs to have 10 characters
string.padStart(10, ‘o’); / / returns' oooooAlice '
// padEnd() 
string.padEnd(10, ‘o’); / / returns' Aliceooooo ';
Copy the code

Asynchronous functions (async/await)

In ES8, the developers provided an alternative to callbacks and promises for asynchronous programming, namely the async/await function. An Async function defines an asynchronous function and returns a Promise that will be resolved or rejected. There is also the.await() operator used in asynchronous functions, which waits for promises. Asynchronous functions provide us with a friendlier syntax. Let’s look at some code

function delayResult() {
    return new Promise(resolve= > {
        setTimeout(() = >{resolve (" Done "); },5000)})}async function getResult() {
    var result = await delayResult();
    return result;
}
getResult();
Copy the code

ES9 (ECMAScript 2018)

Asynchronous iterative

The creators of ES9 added asynchronous iteration, which means you can declare asynchronous loops using await. But it can only be used if the data is from a synchronous source, so we cannot asynchronously iterate over the data from HTTPS FETCH. Let’s look at a code example:

for await (let book of books) { 
     console.log(book) 
};
Copy the code

Rest operator

ECMAScript2019 also brings new behavior to rest operators. It can now copy the remaining object key-value pairs not mentioned in the object literal into the operands. Rest operators should be used at the end; Otherwise, an error will result. Again, you can use it in functions and get the desired attributes. Let’s look at an example to understand it better:

const fruits = { orange: 1.apple: 10.banana: 4,}const{orange,... rest } = fruits;console.log(rest); // { apple: 10, banana: 4 };
// in the function
function getFruits(Apple,... rest) { 
     return rest.banana;
}
Copy the code

Promise.prototype.finally

Another useful feature that comes with ES9 is.finally(), which is another callback function for promises that will be executed whether.then() or.catch() is called. This can be useful if you still need to take some action after the Promise, whether it succeeds or not. Let’s take a look at the code:

const checkResult = () = > new Promise(resolve, reject) => { setTimeout(resolve, 500) }
checkResult()
    .then((result) = > { console.log(result); })
    .catch((error) = > { console.log(error); })
    .finally(() = > { console.log ('Promise finished!’) })
Copy the code

conclusion

We took a look at the most useful (not all) Javascript updates since ES6 in 2015. There are a lot of changes that you probably didn’t know about until today. Remember, it’s important to use it to update your programming knowledge and make your code smarter, shorter, and clearer.