Listen
Copied RSS Feed

JavaScript

What’s New in JavaScript: ECMAScript 2024 (Edition 15)

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!

Syncfusion JavaScript UI controls are the developers’ choice to build user-friendly web applications. You deserve them too.

Grouping synchronous Iterables with the groupBy method

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!

What is groupBy?

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 }
  ]
}

Promise.withResolvers()

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));

Every property of the Syncfusion JavaScript controls is completely documented to make it easy to get started.

Temporal

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.

Regular expression v flag

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", "Ω", "Ω", "ß", "漢", "字"]

To make it easy for developers to include Syncfusion JavaScript controls in their projects, we have shared some working ones.

Simplifying asynchronous code with Top-Level Await

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

Well-formed methods

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:

  • isWellFormed(): To check whether the string is properly encoded according to Unicode standards. If the string contains any invalid sequences, it returns false.
  • toWellFormed(): To return a new string where any malformed sequences are replaced with the Unicode replacement character � (Often referred to as the replacement character). This ensures the string is well-formed, even if it originally contained errors.

Easily build real-time apps with Syncfusion’s high-performance, lightweight, modular, and responsive JavaScript UI components.

Conclusion

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.

  • Grouping synchronous iterables with the groupBy method offers an elegant way to categorize and manage data collections, simplifying data processing tasks.
  • Promise.withResolvers method provides a more controlled and accessible way to handle asynchronous operations, offering developers a streamlined approach for managing promises in their code.
  • Temporal API revolutionizes managing dates and times in JavaScript, offering a modern, precise, and user-friendly alternative to the traditional Date object.
  • Top-Level Await simplifies asynchronous programming by allowing await to be used at the module level, making code cleaner and easier to understand.
  • Regular Expression v Flag introduces new possibilities for complex pattern matching and string manipulation, empowering developers with more expressive and powerful regular expressions.
  • Well-formed Unicode strings ensure that JavaScript handles text data consistently and accurately across different environments, safeguarding against data corruption and enhancing the reliability of internationalized apps.

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 forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Meet the Author

Sathish Kumar Rajendran

Sathish Kumar is the Software Developer for Syncfusion Web Platforms. He has worked on the core architecture for Syncfusion Angular components. He is passionate about web technology and has been active in web development since 2019.