![ES11](https://codesanitize.com/wp-content/uploads/2024/01/ES11.png)
Master JavaScript’s Latest Updates: A Guide to ES11 (ECMAScript 2020):
Here are the key features introduced in ES11 (ECMAScript 2020), with detailed descriptions and examples:
1. Optional Chaining (?.):
- Safely accesses properties of potentially null or undefined objects without errors.
JavaScript
const user = { address: { city: 'New York' } };
const city = user?.address?.city; // 'New York' (without errors if user or address is nullish)
2. Nullish Coalescing Operator (??):
- Provides a default value for expressions that evaluate to null or undefined.
JavaScript
const name = person?.name ?? 'Unknown'; // Assigns 'Unknown' if person.name is nullish
3. Dynamic Import:
- Loads modules dynamically at runtime using
import()
.
JavaScript
const module = await import('./myModule.js');
4. Promise.allSettled():
- Tracks the completion of multiple Promises, regardless of whether they resolve or reject.
JavaScript
Promise.allSettled([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2'),
]).then(results => {
// Handle both resolved and rejected Promises
});
5. String.matchAll():
- Returns all matches of a regular expression in a string, as an iterator.
JavaScript
const matches = 'abc123def456'.matchAll(/\d+/g);
for (const match of matches) {
console.log(match); // Output: ["123", "456"]
}
6. BigInt:
- Represents arbitrarily large integers, beyond the safe integer limit of regular JavaScript numbers.
JavaScript
const bigNumber = 9007199254740991n; // BigInt literal
7. GlobalThis:
- Provides a global object to access global properties and functions in different JavaScript environments.
JavaScript
console.log(GlobalThis === global); // true (in most browsers)
8. Import.meta:
- Provides metadata about the current module, such as its filename and directory.
JavaScript
console.log(import.meta.url); // Logs the URL of the current module