DEV Community

Cover image for The 5 most transformative JavaScript features from ES12
Safdar Ali
Safdar Ali

Posted on

The 5 most transformative JavaScript features from ES12

The release of ECMAScript 2021 (ES12) brought with it several groundbreaking features that have changed how JavaScript developers write and manage code. From simplifying common tasks to introducing more efficient ways to handle data, ES12 significantly improved code readability, maintainability, and performance. In this article, we’ll explore the five most transformative features introduced in ES12 and how they are shaping the future of JavaScript development.

Let’s dive in!

1. Promise.any() – Handling Asynchronous Operations with Ease

Problem Before ES12: JavaScript developers often use Promise.all() and Promise.allSettled() to manage multiple asynchronous operations at once. However, there were scenarios where only the first resolved promise was of interest, and having to wait for all promises to settle wasn’t ideal.

Promise.any() - Safdar Ali

The ES12 Solution: Enter Promise.any(). This feature returns the first fulfilled promise from a group of promises, ignoring those that are rejected. It's perfect for situations where you need the quickest successful result without worrying about any failed ones.

Example:

const promise1 = new Promise((resolve, reject) => setTimeout(reject, 100, 'Error!'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 200, 'Success!'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 300, 'Done!'));

Promise.any([promise1, promise2, promise3])
  .then((result) => console.log(result))  // Output: Success!
  .catch((error) => console.error('No Promises resolved:', error));
Enter fullscreen mode Exit fullscreen mode

Why It Matters: Promise.any() reduces the complexity of handling multiple asynchronous tasks. You no longer need convoluted logic to extract the first successful result, making your asynchronous workflows cleaner and faster.

2. String.prototype.replaceAll() – No More Manual Replacements

*Problem Before ES12: * Previously, JavaScript had replace(), but it only replaced the first occurrence of a substring within a string. Developers had to either manually use regular expressions or chain multiple replace() calls to replace every occurrence of a substring.

The ES12 Solution: The new replaceAll() method does exactly what it sounds like — it replaces all instances of a substring in one go.

Example:

const message = "JavaScript is awesome. JavaScript is flexible.";
const updatedMessage = message.replaceAll("JavaScript", "ES12");

console.log(updatedMessage);  
// Output: "ES12 is awesome. ES12 is flexible."
Enter fullscreen mode Exit fullscreen mode

Why It Matters: This feature simplifies string manipulation, particularly when working with long texts. Gone are the days of using awkward workarounds with regular expressions or loops. It's a straightforward, developer-friendly addition.

3. WeakRefs – Efficient Memory Management

Problem Before ES12: Memory management in JavaScript can be tricky, particularly when it comes to garbage collection. Strong references prevent an object from being garbage collected, which can lead to memory leaks in long-running applications.

The ES12 Solution: WeakRefs provide a solution by allowing developers to hold weak references to objects, meaning they don’t prevent those objects from being garbage collected. This is especially useful in scenarios like caching or working with large datasets where memory optimization is key.

Example:

let cache = new WeakRef({ data: "Large Data Object" });

// Access the object via .deref()
let cachedData = cache.deref();

if (cachedData) {
  console.log(cachedData);
} else {
  console.log('Object has been garbage collected');
}
Enter fullscreen mode Exit fullscreen mode

Why It Matters: WeakRefs empower developers to build more memory-efficient applications, reducing memory leaks and improving performance in large-scale or high-traffic applications.

4. Logical Assignment Operators – Cleaner and More Efficient Code

Problem Before ES12: Assigning values based on conditions required verbose code using conditional statements or multiple lines of assignments.

The ES12 Solution: ES12 introduces logical assignment operators (&&=, ||=, and ??=), which combine logical operations with assignment, providing a concise way to assign values based on conditions.

Example:


let user = { name: "Safdar" };

// Assign a default value only if name is null or undefined
user.name ??= "Default Name";
console.log(user.name);  // Output: "Safdar"

let userPreference = null;

// Assign a value only if userPreference is falsy
userPreference ||= "Dark Mode";
console.log(userPreference);  // Output: "Dark Mode"

Enter fullscreen mode Exit fullscreen mode

Why It Matters: These operators reduce the amount of code you need to write when dealing with conditional assignments, making your code cleaner and more readable. It’s a subtle but powerful addition that can save time and reduce errors.

5. Numeric Separators – Improved Readability for Large Numbers

Problem Before ES12: Working with large numeric literals in JavaScript can be error-prone, as they are often difficult to read at a glance. For example, 1000000000 looks like a blur of zeros without commas or spaces for separation.

The ES12 Solution: Numeric separators allow you to use underscores (_) to group digits in large numbers, improving their readability without affecting their value.

Example:

let largeNumber = 1_000_000_000;
console.log(largeNumber);  // Output: 1000000000
Enter fullscreen mode Exit fullscreen mode

Why It Matters: This simple yet effective feature enhances the clarity of large numbers in your code, reducing the risk of errors when dealing with big datasets, financial calculations, or high-precision applications.

Final Thoughts

ES12 brought a wealth of new features that make JavaScript more efficient, readable, and developer-friendly. From the groundbreaking Promise.any() and replaceAll() methods to practical tools like WeakRefs, logical assignment operators, and numeric separators, these updates are transforming how we write and manage JavaScript code.

If you haven't started using these features yet, now is the perfect time to upgrade your code and take advantage of the cleaner, faster, and smarter workflows offered by ES12. Embrace these changes and watch your JavaScript development process become more efficient than ever.

That's all for today.

And also, share your favourite web dev resources to help the beginners here!

Connect with me:@ LinkedIn and checkout my Portfolio.

Explore my YouTube Channel! If you find it useful.

Please give my GitHub Projects a star ⭐️

Thanks for 30365! 🤗

Top comments (1)

Collapse
 
safdarali profile image
Safdar Ali

Subscribe to my YouTube Channel if you find it helpful! Subscribing is free, and it will motivate me to stay active here. 😊