Uncategorized

These are the new features


No time right now?

New year, new JavaScript features. The release of new ECMAScript versions traditionally takes place in June of each year – we have already looked at the new features planned for 2021 in advance.

The ECMAScript specification is updated annually. Most recently, in 2015, the jump from ECMAScript 5 to ECMAScript 6 was the most comprehensive. In comparison, the innovations to be expected in ECMAScript 2021 are small, but still worth a closer look.

String replaceAll ()

Currently there is no other way to replace all instances of a substring than using replace () in combination with a so-called global regular expression. (/ regexp / g).

const snow = '❄️+☃️+❄️+❆';
const snowWithPenguins = snow.replace(/+/g, '🐧');
console.log(snowWithPenguins); //❄️🐧☃️🐧❄️🐧❆

The new replaceAll () method in ECMAScript 2021 makes the use of a regex obsolete:

Almost finished!

Please click on the link in the confirmation email to complete your registration.

Would you like more information about the newsletter? Find out more now

const snow = '❄️+☃️+❄️+❆';
const snowWithPenguins = snow.replaceAll('+', '🐧');
console.log(snowWithPenguins); //❄️🐧☃️🐧❄️🐧❆

Another example to clarify:

const cuteAnimal = "I love Penguins. Penguins are adorable, especially when they are fishing.";

let newCuteAnimal = cuteAnimal.replaceAll("Penguin", "Bear");

console.log(newCuteAnimal); //I love Bears. Bears are adorable, especially when they are fishing.

In addition, the new replaceAll()Method leads to a small increase in performance, because string comparison is used instead of regular expression comparison.

Promise.any ()

Similar to other Promise methods, Promise.any () iterates over an iterable of Promise objects. Different to Promise.all() stops Promise.any() not as soon as one of the promises is not fulfilled, but runs through the array until one of the promises is fulfilled. If that is the case, the Promise.any()Method returns the value of the first fulfilled promise, the other promises are not checked. If none of the promises in the array are met, the output of Promise.any() rejected with an aggregate error object.

const promise1 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 300, 'not so quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value));

// Expected output: "quick"

Promise.any() is useful for checking that an iterable (array) of promises contains at least one promise that will be met. The method differs from promise.race () in that it does not return the value of the first promise executed, regardless of whether it is fulfilled or rejected, but the first to be fulfilled. Of promise.all() It differs in that not all promises are checked in an iterable and their values ​​- if all are fulfilled – are output in an array.

tldr: Promise.any() takes an iterable of promise objects and resolves when one of the promises resolves. It returns a single promise – the first one to be resolved, with the value from that promise.

Use case: Promise.any() can be used by developers when multiple asynchronous calculations are being performed in an application and only the first successful one is of interest. It can be imagined like a race in which the winner – the fastest calculation – is used:

const myFetch = url => setTimeout(() => fetch(url), Math.floor(Math.random() * 4000));
const promises = [
myFetch('/endpoint-1'),
myFetch('/endpoint-2'),
myFetch('/endpoint-3'),
];

// Example using .then .catch
Promise.any(promises) // Any of the promises fullfilled.
.then(console.log) // e.g. '4'
.catch(console.error); //All of the promises were rejected.

// Example using async-await
try {
const first = await Promise.any(promises); // Any of the promises fullfilled.
console.log(first);
}catch (error) { // All of the promises were rejected
console.log(error);
}

Numerical separators

This new feature improves the readability of numeric literals.
As of ES 2021, an underscore _ can be used as a separator between groups of digits. Theoretically, any number of separators can be used anywhere – it goes without saying that it is advisable to proceed according to a certain system.

const twoBillion = 2000000000;
const twoBillionWithSeparators = 2_000_000_ooo;
const twoBillionAndALittleMore = 1_000_ooo_000.999_999;

Logical Assignment Operator

The new Logical Assignment Operator combines so-called logic operators – AND &&, OR || and zero merge operator ?? with Assignment Expressions =, which results in a slightly shorter syntax. You can read details and code examples in this tooltip.

WeakRef

Objects are heavily referenced in JavaScript by default. This means that referenced objects are not cleaned up, but kept in memory.

let a, b;
a = b = document.querySelector('.refClass')
a = undefined
// ... GarbageCollecting...
// b is still referenced to the DOM-object .refClass

In a scenario in which objects should not be kept in memory indefinitely, so-called weak references can be used with ES 2021 in order to implement caches or mappings, for example on very large objects. WeakRef has the effect that if they are not used, they are cleared from the memory and can be regenerated from the cache if necessary.

Such a weak reference is generated via new WeakRef. The method is used to access the object .deref().

const example = new WeakRef(document.querySelector('.refClass'));
const element = example.deref();

If you want to keep an eye on the further development of the ECMAScript specification until June, you can find it on GitHub Proposals repository.

Most read

Leave a Reply

Your email address will not be published. Required fields are marked *