Ecmascript 15 (2024)

ECMAScript 15 (2024) Features: a complete guide with code examples

Discover all the latest ECMASCRIPT 15 features released in 2024 with code examples

Reading time: 3'

0 likes
Published on October 24, 2024

In the last article, we talked about debounce vs throttle in JavaScript but as JavaScript keeps evolving, it is time to discover the latest ECMAScript 15 (or ES2024 or ES15) features. ES15 brings even more exciting features to make your code cleaner, faster, and more maintainable, so I decided to cover the ECMAScript 15 features you need to know about, along with examples to help you apply them in real-world coding. Are you ready to become a better Frontend Developer?

ES15 Features: the Pipeline Operator

The pipeline operator is one of the most anticipated features of ECMAScript 15. It allows for a more readable function call chain, especially when functions need to be applied sequentially.

Instead of nesting multiple functions, the pipeline operator makes your code easier to follow by chaining function calls more naturally.

const double = (x) => x * 2; const increment = (x) => x + 1; let result = 5 |> increment |> double; console.log(result); // Output: 12

Here, 5 is passed through the increment function first and then through the double function, all in a clean and readable sequence. This operator reduces the need for deeply nested function calls, making code much more manageable.

ES15 Features: do expressions

The do expression allows you to execute blocks of code as expressions and return a value from them. This is handy when you need conditional logic or computations inline.

let value = do { if (someCondition) { 'Success'; } else { 'Failure'; } }; console.log(value); // Output: 'Success' or 'Failure'

This way, instead of traditional conditionals, do expressions allow for flexible block-based expressions with a returned value.

ES15 Features: async context manager

Another great feature introduced in ECMASCRIPT 15 is the async context manager. It simplifies the management of resources in asynchronous operations. This is inspired by Python's with statement and helps manage resources like file handles, database connections, and network streams, ensuring proper cleanup.

async with (const db = await connectToDatabase()) { await db.query('SELECT * FROM users'); } // Automatically closes the database connection after the block

This makes handling resources in an async environment simpler, reducing boilerplate code like manually closing connections.

ES15 Features: immutable array methods

ECMAScript 15 introduces non-mutating methods for arrays: toSorted, toReversed, and toSpliced. These methods return a new array without altering the original array, supporting immutability, which is crucial in functional programming.

let numbers = [4, 2, 7, 1]; // Non-mutating methods let sorted = numbers.toSorted(); let reversed = numbers.toReversed(); let spliced = numbers.toSpliced(1, 2); console.log(sorted); // Output: [1, 2, 4, 7] console.log(reversed); // Output: [1, 7, 2, 4] console.log(spliced); // Output: [4, 1] console.log(numbers); // Original array unchanged: [4, 2, 7, 1]

ES15 Features: symbol metadata for Metaprogramming

With Symbol.metadata, ECMAScript 15 enhances metaprogramming by allowing developers to attach and retrieve metadata to/from class members and methods.

class MyClass { @Reflect.metadata('role', 'admin') doSomething() {} } const metadata = Reflect.getMetadata('role', MyClass.prototype, 'doSomething'); console.log(metadata); // Output: 'admin'

This new feature allows for dynamic reflection and more sophisticated metaprogramming capabilities.

ES15 Features: Promise.withResolvers()

Finally, we have a really great feature about Promises: Promise.withResolvers(). This method simplifies promise management by returning both the promise and its resolve and reject functions.

const { promise, resolve, reject } = Promise.withResolvers(); setTimeout(() => resolve('Data loaded!'), 2000); promise.then((message) => { console.log(message); // Output: 'Data loaded!' });

This removes the need to define resolve and reject separately, cleaning up promise-based code.

ES15 Features: array grouping

Great improvements also onto the array side with new grouping methods: groupBy and groupByToMap.

With the new groupBy method, you can group array elements based on a criterion, creating a more intuitive way to work with large datasets.

const items = [ { type: 'fruit', name: 'apple' }, { type: 'vegetable', name: 'carrot' }, { type: 'fruit', name: 'banana' } ]; const grouped = Array.groupBy(items, item => item.type); console.log(grouped); // Output: { fruit: [{...}, {...}], vegetable: [{...}] }

This feature simplifies grouping operations without manually looping through data.

ES15 Features: Decorators

We finally have Decorators in JavaScript thanks to ECMAScript 15, allowing you to add behaviour or modify classes/methods declaratively. It is gonna be a real game changer in your code.

function logMethod(target, key, descriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args) { console.log(`Called ${key} with arguments: ${args}`); return originalMethod.apply(this, args); }; return descriptor; } class Car { @logMethod drive(speed) { console.log(`Driving at ${speed} km/h`); } } const myCar = new Car(); myCar.drive(100); // Output: "Called drive with arguments: 100" // "Driving at 100 km/h"

Recap ECMASCRIPT 15 features

ECMAScript 15 is packed with features like the pipeline operator, do expressions, async resource management, immutable array methods, and more. These features improve JavaScript by reducing complexity, improving readability, and supporting immutability and metaprogramming.

Whether you're working with promises, handling async operations, or grouping data, these new tools offer cleaner and more efficient solutions. Stay updated, start incorporating these features into your projects, and surprise your peers!

In case you think this content deserves to be shared, it would be great if you could support me just doing at least one of the following actions:

  • Leave a like
  • Leave a comment
  • Share the article
  • Spread the voice with your friends

Articles related to JavaScript

Courses of JavaScript

  • Masterclass19% off
    Max 6 students
    Masterclass JavaScript

    Building a scalable app with NextJS and GraphQL

    NextJS, Graphql, Tailwind and Strapi. The most important technologies in a single masterclass.

    • JavaScript
    • NextJS
    More info
  • Masterclass
    Max 10 students
    React masterclass

    Build your portfolio with ReactJS and Typescript

    Master ReactJS and Typescript by building your own portfolio with NextJS in only 12.5 hours.

    • JavaScript
    • NextJS
    More info

Newsletter

Subscribe to the newsletter to receive updates about programming news, course discounts, and other content published on the platform.
You will get instantly a 10% discount.