Home >Web Front-end >JS Tutorial >What's New in JavaScript: ECMAScript Edition
TL;DR: Discover the groundbreaking features of JavaScript ECMAScript 2024. This guide explores the latest innovations designed to transform your coding experience. From the new groupby method for effortless data grouping to the game-changing Temporal API that simplifies date and time management, ECMAScript 2024 is packed with tools that enhance efficiency and precision.
ECMAScript is a fundamental component of JavaScript. Since the middle of the 1990s, ECMAScript has evolved to provide developers with new capabilities, enriching the dynamic and user-friendly nature of web experiences. From simple scripts to intricate frameworks, it influences the digital landscape and fuels creativity and innovation in web development.
Over the years, numerous editions of ECMAScript have been released, each bringing new features and improvements. In this guide, I will explain what’s new in the latest ECMAScript 2024(Edition 15). Get ready to explore the latest features that are set to revolutionize the way we code!
JavaScript developers often need to organize data into groups based on specific criteria. The new groupBy method in ECMAScript 2024 makes this task a breeze. Imagine you have a collection of items and want to group them by a specific property – groupBy is your go-to tool for that!
The groupBy method is a static method that is available on Object and Map. It allows you to quickly and efficiently group items in a collection based on a key derived from each item. The result is a new object where each key corresponds to a group, and the value is an array of items that belong to that group.
Let’s say you have an array of people, and you want to group them by their age. Here’s how you can do it using the groupBy method.
const people = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 25 }, { name: "David", age: 30 }, { name: "Eve", age: 35 } ]; const groupedByAge = Object.groupBy(people, person => person.age); console.log(groupedByAge);
Output
{ "25": [ { "name": "Alice", "age": 25 }, { "name": "Charlie", "age": 25 } ], "30": [ { "name": "Bob", "age": 30 }, { "name": "David", "age": 30 } ], "35": [ { "name": "Eve", "age": 35 } ] }
JavaScript promises have always been our trusty companions for managing asynchronous operations. But with ECMAScript 2024, there’s a new tool in town: Promise.withResolvers(). This powerful static method gives you the keys to fully control a promise’s fate directly from external code, whether it resolves or rejects.
This Promise.withResolvers() function returns an object with three properties: a new promise with the resolve and reject functions associated with it.
Let’s say you’re managing a task that can be completed or canceled based on user input. Here’s how you can use the Promise.withResolvers() function.
function createControllablePromise() { const { promise, resolve, reject } = Promise.withResolvers(); // Simulate an async task. setTimeout(() => { console.log("Task is pending..."); }, 1000); return { promise, resolve, reject }; } const { promise, resolve, reject } = createControllablePromise(); // Somewhere in your code, you can resolve or reject the promise. setTimeout(() => { resolve("Task completed successfully!"); // or if something goes wrong. reject("Task failed due to an error."); }, 3000); promise .then(result => console.log(result)) .catch(error => console.error(error));
Have you ever struggled with JavaScript’s Date API? It can be pretty challenging.
In ECMAScript 2024, a modern and powerful API called Temporal is designed to make working with dates and times easier, more intuitive, and more accurate. This game-changing API fixes the quirks of the old Date object and brings a host of new features.
The Temporal API is JavaScript’s new way of dealing with dates and times. Unlike the old Date API, which can be cumbersome and error-prone, Temporal offers a more precise and flexible approach.
For example, if you’re planning a project deadline 90 days from today, Temporal makes it simple to calculate the exact date.
Refer to the following code example.
// Getting the current date in ISO format. const today = Temporal.Now.plainDateISO(); console.log(today.toString()); // Output: "2024-07-02" // Adding 90 days to the current date to calculate the deadline. const deadline = today.add({ days: 90 }); console.log(deadline.toString()); // Output: "2024-09-30" // Checking how many days remain until the deadline. const daysUntilDeadline = deadline.since(today).days; console.log(`Days until deadline: ${daysUntilDeadline}`); // Output: "Days until deadline: 90"
This example shows how Temporal can simplify scheduling tasks, making it an essential tool for any JavaScript developer dealing with time-based operations.
ECMAScript 2024 introduces a new enhancement to regular expressions: the v flag. This addition allows for more sophisticated pattern matching and string manipulation, giving developers greater control over handling complex text-processing tasks.
The v flag is all about precision and expressiveness in regular expressions. It introduces set notation, which makes it easier to define patterns that match specific groups of characters, especially those with particular Unicode properties. This means you can create regex patterns that are more accurate and readable.
Let’s explore how the v flag can be used in a regular expression to match a set of characters based on their Unicode properties.
// Regular expression to match any character with the Unicode property "Letter" (L). const regex = /\p{L}/v; // Test string containing various Unicode characters. const testString = "abc123ΩΩß漢字"; // Matching all characters with the "Letter" property. const matches = [...testString.matchAll(regex)]; console.log(matches.map(match => match[0])); // Output: ["a", "b", "c", "Ω", "Ω", "ß", "漢", "字"]
The JavaScript ECMAScript 2024 introduces Top-Level Await, a game-changer for handling asynchronous operations at the module level. This feature eliminates the need to wrap your code in an async function, making your code more straightforward and easier to maintain.
Traditionally, await could only be used inside async functions, which meant you had to create wrapper functions for any asynchronous operations. Top-Level Await changes that by allowing you to use await directly within the top-level scope of a module. This makes handling asynchronous tasks such as fetching data or loading resources much easier when your module is first loaded.
// data.js const response = await fetch('https://api.example.com/data'); export const data = await response.json(); // main.js import { data } from './data.js'; console.log(data); // Logs the fetched data
Handling Unicode strings is crucial in a globalized web environment where apps must support multiple languages and symbols. ECMAScript 2024 introduces the concept of Well-formed Unicode Strings, which ensures that JavaScript handles Unicode data consistently and reliably across different environments.
A well-formed Unicode string follows the proper encoding rules, ensuring characters are represented correctly. Previously, malformed Unicode strings—those with invalid sequences—could lead to unexpected behavior or errors in JavaScript. This new feature helps to identify and correct these issues, making your code more robust.
Let’s see how you can check if a string is well-formed and how to correct a malformed string.
// Example of a well-formed Unicode string. const string1 = "Hello, InfoWorld!"; // Example of a malformed Unicode string. const string2 = "Hello, \uD800world!"; // \uD800 is an unpaired surrogate // Checking if strings are well-formed. console.log(string1.isWellFormed()); // Output: true (well-formed) console.log(string2.isWellFormed()); // Output: false (malformed) // Correcting the malformed string. console.log(string2.toWellFormed()); // Output: 'Hello, �world!'
In the above code example, we have used the following methods:
Thanks for reading! The ECMAScript 2024(Edition 15) introduces a range of powerful features that enhance JavaScript’s flexibility, reliability, and efficiency, making it even more equipped to handle modern web development challenges.
These enhancements make JavaScript more robust and easier to use, positioning it as a more powerful tool for developing complex, modern web apps. By embracing these features, developers can write more maintainable, efficient, and error-resistant code, ensuring their apps are ready for the future of web development.
Syncfusion JavaScript UI components library is the only suite you will ever need to build an app. It contains over 85 high-performance, lightweight, modular, and responsive UI components in a single package.
If you are an existing customer, you can access the new version of Essential Studio from the License and Downloads page. For new customers, we offer a 30-day free trial so you can experience the full range of available features.
If you have questions, you can contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!
The above is the detailed content of What's New in JavaScript: ECMAScript Edition. For more information, please follow other related articles on the PHP Chinese website!