Matching Strings Against a Regular Expression
It is often needed to match a string against a regular expression to find all matches of the regular expression in the string. Prior to the new feature introduced in ECMAScript 2020, a user had to use the regexp.exec method to match a string against a regular expression. The regexp.exec method returns an array of all matches, and a while statement has to be used to loop over the array to get each match. The new String.prototype.matchAll() method has the syntax str.matchAll(regexp), and it matches a string against a regular expression and returns an iterator over all matched objects. The iterator may be iterated over using a for…of loop to access each match of the regular expression in the string. The advantages of the matchAll() method are that no elaborate exec() method call with a g flag is needed, and the matchAll() is not limited to RegExp objects; it may be used with any JS object, which gets converted to a RegExp object. With exec() only a while loop could be used, but with matchAll() any of the for...of, array spread or Array.from() may be used for iterating over the collection.
Dynamic Import of Modules
- The module may be needed conditionally.
- It may not be known in advance if a module is needed at all, and it may need to be imported on an as-needed basis.
- The module does not exist at load time.
- The module has side effects.
ECMAScript 2020 introduces an import() function to dynamically and asynchronously import modules as needed. Asynchronously implies that the processing of the script continues while the dynamic import is performed. An example of using the dynamic import is in an AJAX request. The import() function may be used with await. An example of using the dynamic import function call is in a <button/> element with onclick=import('/modules/ajax-module.js').
The BigInt Primitive
In a calculation involving integers, if the precision is of significance and is limited only by the available memory, arbitrary precision integers are used. ECMAScript 2020 has added a new number primitive called BigNum for use in calculations involving arbitrary precision integers.
A New Function for Promises
The export statement is used to export functions, objects, and primitive values from within a module to be used for importing with the import statement or function. Often it is needed to aggregate exports, and ECMAScript 2020 has added a new syntax export * as ns from 'module' for exporting all functions, objects, and primitive values as a named export from a module.
Some of the other features include the import.meta object to expose context-specific metadata, such as module’s URL to a module, and a nullish coalescing operator (??) that returns the r.h.s (right-hand side) value if the l.h.s (left-hand side) operand is null or undefined and otherwise the l.h.s operand.