Blog
-
Tech Talks

Level Up Your JavaScript: Exciting New ECMAScript Features on the Horizon

Reading time: ca.
3
minutes

Are you tired of wrestling with JavaScript's infamous Date object? Wish there was a cleaner way to chain those functions without sacrificing readability? Well, there's (probably) an interesting change or two heading your way!

After discussing the interesting niche features in ES2024, we decided to set our sights a bit further and check what's hopefully heading our way in the next ECMAScript release. Keep in mind that these features can still be cancelled in the approval phase, but it's good to know what's out there!

Temporal: finally, a worthy opponent for dates and times

As many of you will agree, the current Date object can feel a bit like a relic from a bygone era. Dealing with time zones, date manipulations, and formatting often sends us scrambling for third-party libraries. The current Date API is a bit of a Frankenstein's monster: stitched together from different standards that don't always play nicely.

The Temporal feature promises to change all that with a standardised and comprehensive way to work with everything from simple dates to complex time durations. One of its key improvements is dedicated objects for different scenarios. No more forcing everything into the confines of a single Date object! Temporal lets you work with plain dates, times, time zones, durations, and more, each with their own specialised methods.

Here's a sneak peek at Temporal in action:

// Creating a date
const today = Temporal.PlainDate.from({ year: 2024, month: 8, day: 7 });
// Adding a week  
const nextWeek = today.add({ weeks: 1 });  
// Formatting the date  
console.log(nextWeek.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }));  
// Output: Wednesday, August 14, 2024


Compare this to the current implementation using Date, and you'll quickly see the difference:


// Creating a date
// Watch out, months are zero-indexed, so 7 = August
const today = new Date(2024, 7, 7);

// Adding a week
const nextWeek = new Date(today); // Create a copy
nextWeek.setDate(nextWeek.getDate() + 7); // Add 7 days

// Formatting the date
console.log(nextWeek.toLocaleDateString(‘en-US’, { weekday: ‘long’, year: ‘numeric’, month: ‘long’, day: ‘numeric’ }));

As you can see, Temporal offers a more intuitive and readable syntax for working with dates and times. Temporal is currently a stage 3 proposal, so it's well on its way to becoming a core part of ECMAScript, and we hope that it will be included in the next release.

Pipeline operators: preventing parenthesis purgatory

We've all been there: you need to apply a series of functions to a value, and you end up with a messy nest of parentheses that's harder to decipher than a doctor's note. Luckily, Pipeline operators are here to help us streamline our code with a more readable and intuitive way to express function chaining.  

Instead of nesting functions within each other, you would be able to use the |> symbol to pass the result of one function as the argument to the next, creating a clean pipeline of operations. Here’s a side-by-side comparison:

// Chained
const result = function3(function2(function1(input)));
 
// Temporary variables
const temp1 = function1(input);
const temp2 = function2(temp1);
const result = function3(temp2);
 
// Pipe
const result = input
|> function1(%)
|> function2(%)
|> function3(%)
   

As you can see, pipeline operators make the code flow more naturally from top to bottom, just like the logical sequence of operations. While some might argue that this is just “syntactic sugar,” there’s no denying the impact on readability.

While still in stage 2, pipeline operators have the potential to be a game-changer for anyone that values clean, maintainable code. We'll have to see how well they integrate with existing libraries and frameworks, but we’re optimistic about their future. Fingers crossed!

Records & Tuples: immutable data structures for more predictability

Just in case you didn't know yet: immutability means creating data structures that cannot be changed after they are created. This might seem counterintuitive at first, especially in a language like JavaScript where we’re used to freely modifying objects and arrays. However, immutability can be a powerful tool if you're looking to write more predictable and maintainable code.

For example, imagine you’re working on a large project with multiple developers, and you have an object representing critical data. If that object is mutable, any part of the codebase could potentially modify it, leading to unexpected side effects and difficult-to-track bugs.

We used to have to rely on internal verbal agreements, but Records & Tuples have the potential to shake things up. These upcoming ECMAScript features provide a way to create truly immutable data structures. Records allow you to define immutable objects, while Tuples allow for immutable arrays. Here's how they work:

// Creating an immutable record
const user = # { id: 1, name: 'Alice' };

// Attempting to modify the record throws an error
user.name = 'Bob';  // TypeError: Cannot assign to property "name" on "#<Record>": not writable

// Creating an immutable tuple
const coordinates = #[10, 20];  
// Accessing elements
console.log(coordinates[0]); // Output: 10

As you can see, any attempt to modify a Record or Tuple directly results in an error. To update the data, you'll have to create a new Record or Tuple with the desired changes. While this might seem like extra work, it's helpful for several reasons:

  • Predictability: once created, a Record or Tuple will always hold the same data, no matter where it’s used in your codebase.
  • Concurrency: you won’t have to worry about data races or unexpected modifications from different threads.
  • Debugging: tracking down bugs becomes easier when you know your data structures cannot be altered unexpectedly.

Records & Tuples are still in stage 2, but their potential impact on JavaScript development is undeniable. They introduce a new level of data integrity and encourage a more functional approach to programming.

Decorators: adding a touch of class

Wouldn't it be nice if we could easily add reusable functionality to our JavaScript classes and methods, without cluttering up their core logic? Say hello to Decorators!

Decorators provide a concise and elegant way to enhance the behaviour of classes and methods. They act like special annotations that you can attach to your code, allowing you to inject additional logic before, after, or even around the execution of a method.

Think of them as adding a little extra spice to your code. Need to log every time a method is called? Want to cache results for performance optimisation? Decorators can handle these tasks gracefully.

Here's a simple example of how you can use a decorator to add caching functionality to a method:

class PersonService {
@cached // Decorator
async getPerson(id) {
// ... Heavy API call
return result;
}
}  

In this example, the @cached decorator (which would be defined elsewhere) would intercept calls to the getPerson method. If the result for a given ID is already cached, it will be returned immediately. Otherwise, the heavy API call will be executed, and the result will be cached for future use.

You may recognise this functionality from libraries and frameworks, but it's great to have this powerful capability added to the language itself. However, be careful when using them in projects! If you don't manage them correctly and communicate them to your fellow developers, they can introduce complexity and cause confusion. As with all powerful tools, use them wisely, and they'll help you write more elegant and efficient JavaScript.

Looking ahead

Of course, these exciting new features are just a glimpse of what's on the horizon for JavaScript. As the language continues to evolve, we can expect even more innovative solutions that will help us to write better, more efficient, and more enjoyable code. Keep an eye on our blogs for highlights on other interesting features!

At Optis, we're passionate about staying ahead of the curve and learning the latest features to use in our projects. Like our style? Make sure to check out our careers page!

Charlotte Van der Voort

August 28, 2024

Read the highlights of our blog

"Each project pushes our skills farther and expands our expertise"

Let's talk!

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
We value your privacy! We use cookies to enhance your browsing experience and analyse our traffic.
By clicking "Accept All", you consent to our use of cookies.