![ES9](https://codesanitize.com/wp-content/uploads/2024/01/ES9.png)
Master JavaScript’s Latest Updates: A Guide to ES9 (ECMAScript 2018)
Here are the key features introduced in ES9 (ECMAScript 2018), with detailed descriptions and examples:
1. Rest/Spread Properties:
- Rest Property: Gathers remaining object properties into a new object, for flexible object manipulation.
JavaScript
const { name, ...otherProps } = person; // name gets the "name" property, otherProps gets the rest
- Spread Property: Spreads properties from one object into another, for easy object copying and merging.
JavaScript
const newPerson = { ...person, age: 35 }; // Copies person's properties and adds an "age" property
2. Asynchronous Iteration:
- for-await-of: Iterates over asynchronous iterables (like data arriving over time), handling each element as it becomes available.
JavaScript
async function fetchUserData() {
const response = await fetch('/users');
const users = await response.json();
for await (const user of users) {
console.log(user);
}
}
3. Promise.prototype.finally():
- Executes a callback regardless of whether a Promise is resolved or rejected, ensuring cleanup actions or logging.
JavaScript
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('I always run!'));
Use code with caution. Learn more
4. RegExp Named Capture Groups:
- Assign names to capture groups in regular expressions for easier extraction and readability.
JavaScript
const match = /(?<name>[A-Z][a-z]+) (?<age>\d+)/.exec("Alice 30");
console.log(match.groups); // { name: "Alice", age: "30" }
5. RegExp Lookbehind Assertions:
- Assert patterns behind a match without including those patterns in the match result, enabling more specific matching rules.
JavaScript
const match = /(?<=abc)def/.exec("abcdef"); // Matches "def" only if preceded by "abc"
6. RegExp dotAll Flag (s):
- Makes the dot (.) match newline characters, allowing for broader pattern matching across multiple lines.
JavaScript
const match = /a.b/s.test("a\nb"); // true with dotAll flag
7. Object.fromEntries():
- Creates an object from a list of key-value pairs, often used with
Object.entries()
for object manipulation.
JavaScript
const entries = [["name", "John"], ["age", 30]];
const person = Object.fromEntries(entries); // { name: "John", age: 30 }