In 2019, JavaScript saw the introduction of several powerful features that enhanced its capabilities and improved developer experience. This article explores the significant additions to JavaScript in 2019, helping you grasp their functionalities and potential use cases.
Optional Catch Binding
Optional catch binding allows developers to omit the error parameter in a try-catch block when the error object is not needed. This feature simplifies error handling and reduces unnecessary code clutter.
try {
// Some code that may throw an error
throw new Error('Something went wrong!');
} catch {
console.log('Caught an error, but no need for the error object.');
}
Benefits of using optional catch binding
- Cleaner code with less clutter from unused variables.
- Encourages more readable error handling.
Nullish Coalescing Operator
The nullish coalescing operator (??) is used to return the right-hand operand (default value) when the left-hand operand is null or undefined. This is particularly useful when differentiating between falsy values and null or undefined.
const userInput = null;
const defaultValue = 'default value';
const output = userInput ?? defaultValue; // returns "default value"
console.log(output);
Examples of nullish coalescing in action
User Input | Output |
---|---|
null | default value |
undefined | default value |
0 | 0 |
” (empty string) | ” (empty string) |
Promise.prototype.finally()
Promise.prototype.finally() is a method that allows you to execute a block of code after a Promise settles, regardless of whether it was fulfilled or rejected. This is particularly useful for cleanup operations or to show loading indicators.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('Fetch attempt finished.'));
Use cases and advantages of finally()
- Ensures cleanup code runs after asynchronous operations.
- Improves user experience by indicating completion.
Array.prototype.flat() and Array.prototype.flatMap()
Overview of the flat() method
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
const nestedArray = [1, 2, [3, 4, [5, 6]]];
const flatArray = nestedArray.flat(2); // returns [1, 2, 3, 4, 5, 6]
console.log(flatArray);
Overview of the flatMap() method
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It’s perfect for combining the operations of map() and flat().
const arr = [1, 2, 3, 4];
const result = arr.flatMap(num => [num, num * 2]); // returns [1, 2, 2, 4, 3, 6, 4, 8]
console.log(result);
Practical examples of both methods
Original Array | flat() | flatMap() |
---|---|---|
[1, [2, [3]]] | [1, 2, 3] | Not applicable |
[1, 2, 3] | Not applicable | [1, 2, 2, 4, 3, 6] |
Object.fromEntries()
Object.fromEntries() transforms a list of key-value pairs into an object. This is particularly useful when working with data from Forms or URL parameters.
const entries = [['name', 'John'], ['age', 30]];
const obj = Object.fromEntries(entries); // returns {name: 'John', age: 30}
console.log(obj);
How it transforms key-value pairs into objects
This function simplifies the conversion of maps or arrays into objects, making data manipulation more straightforward in certain scenarios.
String.prototype.matchAll()
matchAll() method returns an iterator of all results matching a string against a regular expression. Using this method is efficient for extraction of patterns from strings.
const regex = /[a-z]+/g;
const str = 'hello world';
const matches = str.matchAll(regex);
for (const match of matches) {
console.log(match);
}
Key features and examples
Search String | Regex Pattern | Matches |
---|---|---|
‘abc123def456’ | /\d+/g | 123, 456 |
‘foo@bar.com’ | /[a-z]+/g | foo, bar |
Intl.DisplayNames
The Intl.DisplayNames object provides a way to display names of locales, currencies, and languages. This feature simplifies the internationalization of applications.
const regionNames = new Intl.DisplayNames(['en'], {type: 'region'});
console.log(regionNames.of('US')); // "United States"
console.log(regionNames.of('FR')); // "France"
Practical use cases for internationalization
- Localization of user interfaces to improve experience.
- Dynamic presentation of content based on user preferences or settings.
Conclusion
In summary, JavaScript introduced several incredibly useful features in 2019, enhancing the language’s utility and performance. Keeping up-to-date with these advancements is essential for developers to create modern, efficient applications.
FAQ
- What is the nullish coalescing operator?
- The nullish coalescing operator (??) is a logical operator that returns the right-hand operand when the left-hand is null or undefined.
- How does optional catch binding improve error handling?
- Optional catch binding allows you to omit the error object in a try-catch block when it is not needed, leading to cleaner code.
- What does Object.fromEntries() do?
- Object.fromEntries() transforms an array of key-value pairs into an object, making data manipulation easier.
- Why is Promise.prototype.finally() useful?
- Promise.prototype.finally() executes code after a Promise settles, allowing for cleanup or to show completion messages.
- What is the purpose of Intl.DisplayNames?
- Intl.DisplayNames is used for internationalization, providing user-friendly names of languages, regions, and currencies based on locale.
Leave a comment