What are ES2018 - ES9 features?
1. Asynchronous Iteration
This feature provides a new for-await-of
loop to handle promises in an iterable form.
async function* fetchData() {
const data = [1, 2, 3];
for (const num of data) {
await new Promise(resolve => setTimeout(resolve, 1000)); // Simulating async work
yield num;
}
}
async function process() {
for await (const num of fetchData()) {
console.log(num); // Will log 1, 2, and 3 with a 1-second delay between each
}
}
process();
2. Rest/Spread Properties for Objects
ES9 introduced rest and spread operators for objects, allowing you to efficiently copy properties from one object to another or merge multiple objects.
- Rest properties: Allow you to extract remaining properties from an object into a new object.
- Spread properties: Allow you to create a shallow copy or merge objects.
const { a, b, ...rest } = obj;
const newObj = { ...obj };
3. Promise.finally()
The finally()
method was added to promises. It allows you to execute code after a promise settles (either resolved or rejected), regardless of the outcome. This can be useful for cleanup operations like closing files or hiding loading spinners.
4. RegExp Improvements (Named Capture Groups, Lookbehind Assertions, and Unicode Property Escapes)
5. JSON Superset for Strings
ES9 also introduced the ability to handle strings that contain characters like newline and carriage returns in JSON more easily, without having to escape them manually. This is an improvement to JSON parsing.