New features are expected in ES2021

Tram Ho

Every year since 2015, JavaScript has been continuously rolling out updates with interesting features. Although the ES2021 release is still quite far away, we can already predict what will happen as many features have reached stage 4 (the final stage marks that the proposed proposal is complete) and is likely to be included in the specs.

As a developer it’s important to stay up to date with new programming language techniques, and if you feel like you’ve been stumped by the number of updates that JavaScript has made over the years, you can read about. This book The Complete Guide to Modern JavaScript , which covers everything from the basics to the latest ES2020 specifications, includes a little introduction to TypeScript.

Au kei, now let’s get started with our first new ES2021 feature:

1. String.prototype.replaceAll

String.replace is a very useful method that allows us to replace a pattern in a string with the value we passed. The problem is if we want to use a string as a pattern and not RegEx, then it replaces only the first pattern found. Look at the example to understand:

The name says it all, String.replaceAll will do exactly what we need in this case, replacing all matching patterns without using RegEx:

Understand better here, here!

2. Promise.any

Over the years, new methods are constantly being introduced, like Promise.all and Promise.race with ES6, Promise.allSettled last year with ES2020 and ES2021 will introduce a new method: Promise.any

I bet you know what it does from the method name.

Promise.any () will resolve if any promises offered to be resolved. Below we have 3 promises that resolve at random times.

In p1, p2, and p3, whichever resolves first will be done by Promise.any ().

So what if no promises resolve? In that case, Promise.any () throws an AggregateError exception. We need to catch and handle it.

For demo purposes, only one promise is passed to Promise.any (). And that promise is rejected. The code below captures the following error in the console.

You can learn more about it here .

3. Logical operators and assignment expressions

With ES2021, we should be able to combine Logical Operators (&&, || and ??) with an assignment expression (=) similar to how it was possible in Ruby. If you omitted ES2020, you probably don’t know ?? is the nullish coalescing operator. Let’s see an example:

The nullish association operator returns the element to the right when the left side is null or undefined, otherwise it returns the element to the left. In the first example, the element on the left is null so it returns the element on the right while in the second example it returns the left side since it is neither null nor undefined.

Back in ES2021, with new suggestions, we could do the following:

Let’s take a look at each one:

  • a || = b returns a if a is true, and b if a is false
  • c && = d returns d if both c and d are true, otherwise c
  • e ?? = f will return f if e is null or undefined, otherwise it returns e

You can take a closer look here !

4. Number separator

The introduction of the Number Separator will make it easier to read numeric values ​​by using the _ character (underscore) to provide separation between groups of digits.

Although not difficult, but you can e-cloud-zing with other examples here and there, swear ^^!

5. WeakRefs and Finalizers

5.1. WeakRefs

WeakRef stands for Weak References. The main purpose of using WeakRef is to implement caching or mapping to large objects.

In such situations, we don’t want to keep a lot of memory for a long time to save this cache or seldom used mapping. We can allow the memory to be “tidied up” early and later if we need it, we can create a new cache.

JavaScript is a garbage collected language. That is, if a variable is no longer inaccessible, JavaScript will automatically delete it (you can learn more about this “cleanup” herelink )

Take a look at the code below

The code can look complicated. But basically, what we do is create a function called callback () and execute it using setTimeout (). await is a feature in ES6 that helps to execute asynchronous code asynchronously. When executing the above code, it will print “Backbencher” after 2 seconds. Based on how we use fucntion callback (), aBigObj can be stored in memory forever.

Now, try making aBigObj a weak reference (WeakRef)

A WeakRef is created using new WeakRef (). The reference is then read using the .deref () method. Inside the async function, the first setTimeout () will inevitably print the value of name. That definitely happens in the first turn of the loop after the weak reference is generated.

But there’s no guarantee that the second setTimeout () prints out “Backbencher”. It may have been picked up by the Javascript “garbage collector”. Because the “garbage collection” component behaves differently in different browsers, output cannot be guaranteed. That is also why, we use WeakRef in situations like cache management.

5.2. Finalizers

FinalizationRegistry is a companion feature of WeakRef. It allows programmers to “register” callbacks that can be called back after an object has been “cleaned up”.

registry is an instance of FinalizationRegistry . The callback function passed to FinalizationRegistry is activated when an object is cleaned up.

Line 3 attaches an object to the registry. When obj is tidy up, the second argument of the ** .register () ** method is passed to the callback function. So, according to the logic above, when obj is tidy up, ” Backbencher ” is passed to the callback function and printed in the console log. When executing the above code in the Google Chrome Canary console, after about 1 minute, it will print “Backbencher” in the console.

6. Intl.ListFormat

Intl.ListFormat is a constructor – constructor for objects, allowing for flexible formatting of lists according to language (currently supporting 47 languages).

Let’s find out the example below:

Intl.ListFormat is a constructor with 2 parameters:

  • the first parameter is locales – the language tag (‘en-GB’ is English, ‘it’ is Italian, …)
  • The second parameter is the options:
    • style: “long” (default, eg, A, B, and C), “short” or “narrow” (eg, A, B, C), if the style is “narrow” then the type must be “unit”
    • type: “conjunction” (a list of combinations, “and” with English like “and” in Vietnamese), “disjunction” (or / or, …), “unit” for list units of measure (eg, 5 pounds, 12 ounces)

As I said above, it is flexible with different languages, not only used in English, we can use it with different languages:

Learn more here if you want to go deeper

7. Options dateStyle and timeStyle for Intl.DateTimeFormat

We can use dateStyle and timeStyle to request a specific date and time by language and for a certain length.

As for dateStyle:

You can use any language you want and you can also use both dateStyle and timeStyle at the same time, choosing between the three options ‘short’, ‘medium’ and ‘long’ accordingly. tailored to your needs.

8. Private Methods

Private methods can only be accessed within the class for which it is defined. Method names begin with #.

Since setType () is a private method, personObj.setType returns undefined. Trying to use undefined as a function gets a TypeError?

O-cloud-zing, pinnacle. Now wait to use these new things. You can see the new features from ES6 following this article. In viblo

References

Share the news now

Source : Viblo