Introduction to new features of ECMAScript 2021(ES12)

brief introduction

ES12 is a version issued by ECMA Association in June 2021. Because it is the twelfth version of ECMAScript, it is also called ES12

It has been a month since ES12 was released. What are the new features and differences of ES12? Let's have a look.

Basically, ES12 introduces the replaceAll method for String operation, Promise.any for Promise combination operation, AggregateError for representing a collection of multiple errors, and the new logical operators? =, & & =, | =, Weak reference WeakRef, FinalizationRegistry is used for garbage collection registration, and the separator of a number is 1_ 000, a more accurate array sort method Array.prototype.sort.

This article will explain them one by one.

replaceAll

Friends familiar with java should know that there are two methods of string replacement in java, namely replace and replaceAll. The difference between them is that replace is a replacement string and replaceAll is regular expression matching.

However, in javascript, the meanings of the two are different. In JS, replace means to replace the first string, and replaceAll means to replace all strings literally. Let's take an example:

const string="flydean is a good fly"
console.log(string.replace("fly", "butterfly"));

The above value returns:

butterflydean is a good fly

If you use replaceAll instead:

const string="flydean is a good fly"
console.log(string.replaceAll("fly", "butterfly"));
butterflydean is a good butterfly

Private method

Since JS has the concept of class, you can define methods in the class and call them through the instantiated class, as shown below:

class Student {
  getAge() {
    console.log("Forever 18")
  }
}

student= new Student();
student.getAge();

Running result of the above code:

"Forever 18"

However, if we do not want the getAge() method to be directly exposed to external use, that is, we want getAge() to be a private method, we only need to add # before the method.

class Student {
  #getAge() {
    console.log("Forever 18")
  }
}

student= new Student();
student.getAge();

If you run the same, you will get the following error prompt:

Error: student.getAge is not a function

How to deal with it? We know that the private method can be invoked inside the method, so we only need to create a public method and then call the private method in this public method.

class Student {
  #getAge() {
    console.log("Forever 18")
  }
  
  getPublicAge(){
    this.#getAge();
  }
 
}

student= new Student();
student.getPublicAge();

We can get the same result.

Private property

Private methods are mentioned above, so how to deal with private attributes?

Generally, we can modify attributes with the get modifier, and then access them directly through the attribute name:

class Student {
  get Age() {
    return 18;
  }
 
}

student= new Student();
console.log(student.Age);

As a result, we will get 18 outputs.

Similarly, you can add # before the attribute name to make it a private variable, as shown below:

class Student {
  get #Age() {
    return 18;
  }
 
}

student= new Student();
console.log(student.Age);

The above code will output undefined.

To access the above private attributes, you can call the private attribute method with the public attribute:

class Student {
  get #Age() {
    return 18;
  }
   get publicAge() {
    return this.#Age
  }
}

student= new Student();
console.log(student.publicAge);

Very easy to use.

Promise.any() and AggregateError

promise.any can return any early resolve result, which is very common in real applications. Let's simulate an example:

const prom1 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise one"),
    Math.floor(Math.random() * 100)
  );
});
const prom2 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise two"),
    Math.floor(Math.random() * 100)
  );
});
const prom3 = new Promise((resolve, reject) => {
  setTimeout(
    () => resolve("promise three"),
    Math.floor(Math.random() * 100)
  );
});

(async function() {
  const result = await Promise.any([prom1, prom2, prom3]);
  console.log(result); 
})();

The above code can randomly output promise one, promise two, promise three.

If the above code is changed to reject all, an AggregateError will be thrown:

const prom1 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise one rejected"),
    Math.floor(Math.random() * 100)
  );
});
const prom2 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise two rejected"),
    Math.floor(Math.random() * 100)
  );
});
const prom3 = new Promise((resolve, reject) => {
  setTimeout(
    () => reject("promise three rejected"),
    Math.floor(Math.random() * 100)
  );
});

try{
(async function() {
  const result = await Promise.any([prom1, prom2, prom3]);
  console.log(result); 
})();
} catch(error) {
  console.log(error.errors);
}


The errors reported are as follows:

Uncaught (in promise) AggregateError: No Promise in Promise.any was resolved

Note that AggregateError will be thrown only after all promise s are reject ed. If some are successful, successful results will be returned.

Number separator

This new feature is designed to facilitate programmers to look at the code. If the number is large, it doesn't look so clear at a glance, such as the following long numbers:

const number= 123456789;

You can't see at a glance how large the number is, so ES12 provides a number separator.

Separator can not only split decimal, but also split binary or hexadecimal data, which is very easy to use.

const number = 1_000_000_000_000;
const binary = 0b1010_0101_1111_1101;
const hex = 0xAF_BF_C3;

The above examples represent decimal, binary and hexadecimal data respectively, which is very intuitive and easy to use.

New logical operators

We know that & & and 𞓜 are operators used for logical operations.

For example:

1 && 2 
1 || 2 

ES12 provides binary operators of & & and |, as follows:

var x = 1;
var y = 2;
x &&= y;
x ||= y;

In addition, it also provides?? Binary operators, such as:

var x;
var y = 2;
x ??= y;

The meaning of the above code is to judge whether x is empty. If it is empty, assign the value of y to X.

summary

Several new features of ES12 are still very practical. You can try them.

Tags: Javascript regex ECMAScript

Posted by golfinggod on Wed, 22 Sep 2021 10:34:01 +0530