Javascript. 5 news that ES2021 will bring us
Discover the new features that Javascript will incorporate in the next revision of the language
Since ES6 was released back in 2015, year after year Javascript has received interesting news that improve the way we work with this language.
It is true that none have been the revolution that at the time meant the features incorporated with EcmaScript 2015 (spread operator, promises …), but they have contributed to making Javascript an increasingly mature language.
Now that we are at the end of 2020, it is time to review everything that is to come next year with the release of ES2021
Logical assignments
If you do not know the “shortcircuits” of Javascript the first thing I recommend is that you visit this page:
As you have seen, the operator ||
could be used for assigning default values:
let bar;
const foo = 'some value';
bar = bar || foo;
Starting in 2021 we will be able to carry out this assignment in a shorter way thanks to the operator ||=
:
let bar;
bar ||= 'some value';
In addition to it, the &&=
operator has also been incorporated:
let foo = 'foo';
let bar = 'bar';
foo = foo && bar; // 'bar'foo &&= bar; // 'bar'
And the ??=
operator, which uses the null coalescing operator to perform the assignment:
let foo = null;
let bar = 'bar';foo = foo ?? bar; // 'bar'foo ??= bar; // 'bar'
String.prototype.replaceAll
In Javascript, the replace
method that strings have has a characteristic that is not entirely intuitive. If the first argument is a string, only the first occurrence will be replaced:
const p = 'These are foo, foo, and foo.';
p.replace('foo', 'bar'); // 'There are bar, foo, and foo.'
For the method to work as we surely expect, it is necessary to pass the string as a regular expression:
const p = 'These are foo, foo, and foo.';
p.replace(/foo/g, 'bar'); // 'There are bar, bar, and bar.'
Something that is not entirely comfortable.
However, ES2021 introduces the replaceAll
method that directly replaces all occurrences with the string we specify:
const p = 'These are foo, foo, and foo.';
p.replaceAll('foo', 'bar'); // 'There are bar, bar, and bar.'
This method, like replace, does not modify the original string but returns a new one with the result of the replacement.
Promise.any
The any method of the Promise object returns a promise as soon as one of the passed as arguments goes to the “fullfilled” state. The difference with the Promise.race
method is that this method does not throw an exception if the first promise to execute fails. It just throws an exception in case all the promises in the array end in the rejected state.
Invocation of Promise.any
with an array of promises where at least one is resolved correctly:
const promises = [new Promise((resolve, reject) => reject('Primera')),new Promise((resolve, reject) => reject('Segunda')),new Promise((resolve) => resolve('Tercera'))];Promise.any(promises).then(result => console.log(result)); // 'Tercera'
Invocation of Promise.any
with an array of promises that all fail:
const promises = [new Promise((resolve, reject) => reject('Primera')),new Promise((resolve, reject) => reject('Segunda')),new Promise((resolve, reject) => reject('Tercera'))];Promise.any(promises).then(result => console.log(result)).catch(error => console.log(error)); // AggregateError: All promises were rejected
Numeric separators
A very simple feature that will make our code more readable is the possibility of using the _
character to separate groups of digits from a number:
const number = 1_000_000_00;
console.log(number); // 100000000
Intl.ListFormat
The Javascript Intl class allows us to natively translate dates and monetary amounts into different languages:
In ES12 a new method is added, Intl.ListFormat
:
const people = ['Pepito', 'Fulanito', 'Menganito'];new Intl.ListFormat('es', { style: 'long', type: 'conjunction' }).format(people);
// "Pepito, Fulanito y Menganito"new Intl.ListFormat('es', { style: 'long', type: 'disjunction' }).format(people);
// "Pepito, Fulanito o Menganito"
WeakRef
In a previous article I already told you about the WeakMaps:
Now ES2021 incorporates the WeakRef
object to define weak references to variables so that they do not count when they are eliminated by the “garbage collector”.
Javascript’s “garbage collector” is responsible for automatically eliminating all those variables that are no longer being used in any part of the code, so that memory is optimized.
Let’s see the use of WeakRef
with a very simple example in which we define a time interval that swaps the style of a link until it disappears.
function toggleUnderline(element) {
const weakElement = new WeakRef(element);
let intervalId = null;
function toggle() {
// Obtener el elemento de la Weak Reference
const el = weakElement.deref();// Puede que ya no exista
if (el) {
const decoration = weakElement.style.textDecoration;
if (decoration === 'none') {
weakElement.style.textDecoration = 'underline';
} else {
weakElement.style.textDecoration = 'none';
} else {
clearInterval(intervalId);
}
}
intervalId = setInterval(toggle, 1000);
}toggleUnderline(document.getElementById("animatedLink"));setTimeout(() => {
document.getElementById("animatedLink").remove();
}, 10000);
This WeakRef
object can be very useful for implementing caches and if you want to know more about it I advise you to read this article carefully:
Final thoughts
As you can see, the year 2021 will not bring us many new features in terms of “super” interesting features. However, I think this is because Javascript will gradually reach a high degree of maturity, so now the developer team is focusing on improving some of its features.