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

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

As a back-end dish, in fact, should write more back-end things, but students like to see the front end of the article. There is no way out 🙄, two days ago, I saw a student in the gold digging group did not know where to see the new features of ES and the corresponding relationship between ES specification and new features. I think my opportunity comes to 🤣. I have been busy for two days. Today, I will spare some time to give you a popular science, and by the way, I will tell you what es2016-ES2022 has in the end.

ES is what?

ES stands for ECMAScript, a scripting language specification defined by ECMA International (formerly known as the European Computer Manufacturers Association) in the standard ECMA-262. It has been released annually since 2015 and is the thirteenth version by ES2022. The JavaScript we commonly use is an implementation and extension of the ECMA-262 standard. Now I will directly paste an official website address ECMAScript, you can see the detailed content of the official website. I’m not going to talk much about this. There is no need to… 🤥

Although ES2022 hasn’t been officially released yet, the proposal is done and done. Below I will list the full name, release year and abbreviated information of each ES version proposal according to the general situation, so that we will not confuse the name of ES.

The full name Year published Abbreviation/abbreviation
ECMAScript 2015 2015 ES2015 / ES6
ECMAScript 2016 2016 ES2016 / ES7
ECMAScript 2017 2017 ES2017 / ES8
ECMAScript 2018 2018 ES2018 / ES9
ECMAScript 2019 2019 ES2019 / ES10
ECMAScript 2020 2020 ES2020 / ES11
ECMAScript 2021 2021 ES2021 / ES12
ECMAScript 2022 2022 ES2022 / ES13

Some students may wonder why ES2015 corresponds to ES6 instead of ES5. To clarify, the two numbers are not the same thing. 2015 is the date of release, and 6 is the number of versions of the ECMAScript language specification. So if you don’t understand, maybe you will understand, and then go back and look at the table above, and you will be even more impressed.

Es2016-es2022 features

Without further ado, let’s get right to it. I will divide the content of ES2016-ES2022 into sections for example demonstration, mainly in the order of completed proposals on Github. (PS: Start from ES2016 / ES7 without ES2015 / ES6)

ES2016 / ES7

Array.prototype.includes Whether the Array contains an element

The main function of this feature is to find if an element is in an array. Before this method came out, the lazy student might have checked the array using indexOf

[1.2.3].indexOf(1) > =0

// Result: true
Copy the code

Normally, there is nothing wrong with indexOf, but there is a loophole in this method. If the element to be viewed is NaN, the indexOf method will not be able to accurately determine whether the element is contained in the array

[1.2.NaN].indexOf(NaN) > =0

// Result: false
Copy the code

Another problem is that the indexOf mainly wants to show that this method is one of the elements in the array index position Rather than to determine whether an element is included in the array, so hard-working students usually by writing a loop method to deal with this problem, but refer to this method is more troublesome, directly set on the prototype? Dare not dare…

function contains(array, val) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] === val) {
            return true; }}return false;
}
Copy the code

Now that we have the includes method, all of the above problems will be solved and made more efficient. Let’s test the following code and you can imagine the results

console.log([1.2.3].includes(2) = = =true);
console.log([1.2.3].includes(4) = = =false);
console.log([1.2.NaN].includes(NaN) = = =true);

console.log([1.2, -0].includes(+0) = = =true);
console.log([1.2, +0].includes(-0) = = =true);

console.log(["a"."b"."c"].includes("a") = = =true);
console.log(["a"."b"."c"].includes("a".1) = = =false);
Copy the code

We will now publish the answer, the above seven results are true. There is no doubt that…

Exponentiation operator Exponentiation

This is not much to say, just look at the code snippet below

let squared = 2 ** 2;
// same as: 2 * 2

let cubed = 2 ** 3;
// same as: 2 * 2 * 2

let a = 2;
a **= 2;
// same as: a = a * a;

let b = 3;
b **= 3;
// same as: b = b * b * b;
Copy the code

ES2017 / ES8

Object.values/object. entries Object values and Object pairs

The object. values method returns an array of all the enumerable property values of a given Object itself, in the same order as the values used for… The in loop is in the same order (the difference is that the for-In loop enumerates the properties in the prototype chain), look at the code

let point = {x: 12.y: 6};
Object.values(point);

// Result: [12, 6]
Copy the code

The object. entries method returns an array of key-value pairs for the given Object’s own enumerable properties, arranged in the same order as for… The in loop returns the same order as it iterates through the object (the difference is that for-In also enumerates the properties in the prototype chain).

It sounds a little convoluted, but let’s just look at the code

let point = {x: 12.y: 6};
Object.entries(point);

[["x", 12], ["y", 6]]
Copy the code

Strings are also ok

Object.entries("hello world");

/ / the result: [[" 0 ", "h"], [" 1 ", "e"], [" 2 ", "l"], [" 3 ", "l"], [" 4 ", "o"], [" 5 ", ""], [" 6", "w"], [" 7 ", "o"], [" 8 ", "r"], [" 9 ", "l"], [" 10 ", "d"]]
Copy the code

Let’s try the order

let object = {
    3: "z".1: "x".2: "y".z: 3.x: 1.y: 2
};

for (var key in object) {
    console.log(key);
}
/ / 1
/ / 2
/ / 3
// z
// x
// y

Object.entries(object);

/ / result: [[" 1 ", "x"], [" 2 ", "y"], [" 3 ", "z"], [" z ", 1], [" x ", 2], [3] "y",]
Copy the code

As we can see, the output is consistent with our method description above. The in loop iterates through the object in the same order. Also, there’s a hidden buff, for… In will put the key of the number type in ascending order. If you don’t believe it, you can try it yourself.

String. The prototype. PadStart/String. Prototype. PadEnd fill the String

These two methods are fairly common, I can specify the maximum width of a character, truncate the replacement character when the string exceeds the maximum length, keep the left side (padStart) or the right side (padEnd) and if the string width is not reached, Will fill the specified character at the beginning (padStart) or the end (padEnd). The fill character is not specified and defaults to a space (U+0020). It is mainly used to format strings, but you can also play with it. Let’s look at the definition first

interface String {
    /** * Populates the current string with the given string (possibly repeated) to produce a string of the given length. The fill is applied from the beginning of the current string (left). * *@param MaxLength Specifies the length of the string after filling the current string. If this parameter is less than the length of the current string, the current string is returned as is. * *@param FillString String used to fill the current string. If the string is too long, it is truncated and the leftmost portion is applied. The default value of the argument is "(U+0020). * /
    padStart(maxLength: number, fillString? :string) :string;

    /** * Populates the current string with the given string (possibly repeated) to produce a string of the given length. Apply padding from the end of the current string (to the right). * *@param MaxLength Specifies the length of the string after filling the current string. If this parameter is less than the length of the current string, the current string is returned as is. * *@param FillString String used to fill the current string. If the string is too long, it is truncated and the leftmost portion is applied. The default value of the argument is "(U+0020). * /
    padEnd(maxLength: number, fillString? :string) :string;
}
Copy the code

Some of you may be confused about the meaning of the truncation above, but let’s go ahead and look at the output

'foo'.padStart(5)
// Result: 'foo'
'foo'.padStart(5.The '-')
// Result: '--foo'
'foo'.padStart(5.'xyz')
// result: 'xyfoo' (out of length, 'z' character truncated, left portion preserved)
'bar'.padEnd(5)
// result: 'bar '
'bar'.padEnd(5.The '-')
// result: 'bar--'
'bar'.padEnd(5.'xyz')
// result: 'barxy' (the 'z' character is truncated to keep the left part)

// The original string length exceeds the maximum string length
'foo'.padStart(2.'xyz')
// Result: 'foo'
'foo'.padStart(2.'xyz')
// Result: 'foo'
Copy the code

Descriptor Object. GetOwnPropertyDescriptors itself attribute

This method can be understood in terms of the meaning of the method, which is to get the descriptor of its own property. It often works with the object.create () method to copy Object properties/Object property properties and stereotypes. Before we can understand this approach, we need to know what a property descriptor is. We first define an object print hand that directly gets the object’s property descriptor

let point = {
    x: 12.y: 16.move({x, y}) {
        this.x = x;
        this.y = y; }}Object.getOwnPropertyDescriptors(point);
/ / {
// x: {
// configurable: true,
// enumerable: true,
// value: 12,
// writable: true,
// [[Prototype]]: Object
/ /},
// y: {
// configurable: true,
// enumerable: true,
// value: 16,
// writable: true,
// [[Prototype]]: Object
/ /},
// move: {
// configurable: true,
// enumerable: true,
// value: f move({x,y}),
// writable: true,
// [[Prototype]]: Object
/ /},
// [[Prototype]]: Object
// }

let c = {}
Object.getOwnPropertyDescriptors(c);
/ / {}
Copy the code

We can see from the above result: if the object is empty, then the description obtained is an empty object. If there are attributes or methods, each attribute will be described, including

  • Different: Works if and only if this property is configuredconfigurableThe key value fortrue, the descriptor of the attribute can be changed, and the attribute can also be deleted from the corresponding object.The default isfalse
  • Enumerable: If and only if this propertyenumerableThe key value fortrueThe property appears in the enumeration property of the object.The default isfalse.
  • Value: indicates the value of the attribute. It can be any valid JavaScript value (numeric value, object, function, etc.). The default is undefined.
  • Writable: If and only if this propertywritableThe key value fortrue, the value of the property, which is the one abovevalueTo beThe assignment operatorChange.The default isfalse.

We can see the details here in Object.defineProperty(), where the property descriptor is actually used for the third argument to Object.defineProperty(). Enumerable, Writable, cis, cis, cis, cis, cis, cis, cis, CIS, CIS, CIS, CIS, CIS, CIS, CIS, CIS, CIS

Let’s now modify the above example to make it more understandable. So let’s go through and print the key for point

for (var key in point) {
    console.log(key);
}
// x
// y
// move
Copy the code

Then change the descriptor of point’s move method using the object.defineProperty () method

Object.defineProperty(point, 'move', {
    enumerable: false
});
for (var key in point) {
    console.log(key);
}
// x
// y
Copy the code

We can see the move method in the for.. There is no print name in in. We use the Object. GetOwnPropertyDescriptor () the old way To see a move the properties of the descriptor

Object.getOwnPropertyDescriptor(point, 'move');
/ / {
// configurable: true,
// enumerable: false,
// value: f move({x,y}),
// writable: true,
// [[Prototype]]: Object
/ /}
Copy the code

In line with our expectations. Now that you understand the property descriptor, you can make sense of this new method

Async functions Asynchronous methods

There is nothing to write about this feeling. Async and await are syntactic candy, and async flagged methods will return a Promise object. We can await a Promise object in an async tagged method and wait until the next statement is executed. This allows us to write asynchronous promises in async tagged methods with synchronous methods. Let’s take a quick example

async function a() {
    return "a";
}
function b() {
    return new Promise((resolve, reject) = > {
        setTimeout(() = > {
            resolve("b");
        }, 3000);
    });
}
async function c() {
    return "c";
}
async function d() {
    let a = await a();
    console.log(a);
    let b = await b();
    console.log(b);
    let c = await c();
    console.log(c);
}
console.log(d())

/ / the result:
// Promise {
      
       } 'async' flags a method that returns a 'Promise' object
      
// a
// b Wait three seconds and continue output
// c

Copy the code

The asynchronous method, written synchronously, looks nice, but is a bit of a problem in practice. I wrote an article about using async await in JS. If you are interested, you can read it.

Shared memory and atomics

This is a specification for the browser, we can use SharedArrayBuffer and Atomics to enhance the parallelism of JS. If you want to know more about SharedArrayBuffer and Atomics, you can browse SharedArrayBuffer and Atomics, because there are few scenarios, I won’t go into details. Come on, guys.

conclusion

I’m going to stop here. I started the article with the headline: a Quick Look at the new ES2016-ES2022 features. But writing it down, ES7 and ES8 are already too long for me to explain, so I’m going to break down the new features of ES2016-ES2022 into several articles. The purpose is to make it easier for you to understand the content (it’s not 😝), to give you and myself some leeway. Hee hee


If the article is helpful to you, welcome to like, comment, pay attention to, collect, share, your support is my code word power, thank you!! 🌈

If the content of the article is wrong, welcome to correct, exchange, thank 😘

Finally, you can click here to join the QQ group FlutterCandies🍭 and communicate with various gurus

The resources

  • Introduction to EMACScript and the latest specification
  • The completed ES proposal
  • Async await is gracefully used in JS