ECMAScript 2021 (ES12)

Welcome to TheCodingCollege.com! ECMAScript 2021 (ES12) introduced several enhancements to streamline JavaScript programming. These features focus on code clarity, error handling, and improved data handling for modern applications.

This guide will cover:

  1. New features introduced in ECMAScript 2021.
  2. Real-world examples for better understanding.
  3. How ES12 can improve your JavaScript development.

Key Features of ECMAScript 2021

  1. Logical Assignment Operators
  2. Numeric Separators
  3. String replaceAll()
  4. WeakRefs and FinalizationRegistry
  5. Promise.any()
  6. Improved Error Handling
  7. New Array and TypedArray Methods

1. Logical Assignment Operators

Logical assignment operators combine logical operations (&&, ||, and ??) with assignment, simplifying common patterns.

Example:

let x = 5;
let y = null;

// Logical OR assignment
x ||= 10; // x remains 5
y ||= 10; // y becomes 10

// Logical AND assignment
x &&= 20; // x becomes 20
y &&= 30; // y remains 10

// Nullish coalescing assignment
y ??= 50; // y remains 10

Benefits:

  • Reduces code repetition.
  • Combines logic and assignment in a concise way.

2. Numeric Separators

Numeric separators (_) improve readability of large numbers.

Example:

const largeNumber = 1_000_000; // Easier to read than 1000000
const hexValue = 0xAB_CD_EF;
console.log(largeNumber, hexValue); // 1000000 11259375

Why Use It?

  • Makes large numbers more human-readable without affecting performance.

3. String replaceAll()

The replaceAll() method replaces all occurrences of a substring or pattern in a string.

Example:

const text = "foo bar foo";
const replaced = text.replaceAll("foo", "baz");

console.log(replaced); // "baz bar baz"

Use Cases:

  • Easier string manipulation without relying on regular expressions.

4. WeakRefs and FinalizationRegistry

WeakRefs allow you to hold weak references to objects, preventing memory leaks. FinalizationRegistry lets you register cleanup actions when an object is garbage collected.

Example: WeakRefs

let obj = { key: "value" };
const weakRef = new WeakRef(obj);

console.log(weakRef.deref()?.key); // "value"
obj = null; // The object is eligible for garbage collection
console.log(weakRef.deref()); // undefined

Example: FinalizationRegistry

const registry = new FinalizationRegistry((key) => {
  console.log(`${key} object is garbage collected.`);
});

let obj = { name: "example" };
registry.register(obj, "example");

obj = null; // Triggers the registry callback upon garbage collection

Benefits:

  • Useful for managing memory in advanced applications.
  • Enables custom cleanup tasks.

5. Promise.any()

Promise.any() returns the first promise that resolves, ignoring rejected ones. If all promises reject, it throws an AggregateError.

Example:

const promises = [
  Promise.reject("Error 1"),
  Promise.resolve("Success!"),
  Promise.reject("Error 2"),
];

Promise.any(promises)
  .then((value) => console.log(value)) // "Success!"
  .catch((error) => console.error(error));

Why It’s Useful:

  • Efficiently waits for the first successful result without being affected by errors.

6. Improved Error Handling

The Error object now includes a cause property to provide additional context.

Example:

try {
  throw new Error("Something went wrong!", { cause: "Invalid input" });
} catch (err) {
  console.log(err.message); // "Something went wrong!"
  console.log(err.cause);   // "Invalid input"
}

Benefits:

  • Simplifies debugging by including contextual information.

7. New Array and TypedArray Methods

Array.prototype.at()

The at() method retrieves an element by its index, supporting negative indexing.

Example:

const arr = [10, 20, 30, 40];

console.log(arr.at(1));  // 20
console.log(arr.at(-1)); // 40

Benefits:

  • Easier to access elements, especially from the end of an array.

Why Use ECMAScript 2021?

  1. Enhanced Readability: Numeric separators and replaceAll() make code clearer and more maintainable.
  2. Better Memory Management: WeakRefs and FinalizationRegistry provide advanced control over garbage collection.
  3. Simplified Promises: Promise.any() offers an alternative way to handle asynchronous workflows.
  4. Improved Debugging: The cause property in errors adds valuable context.

Explore JavaScript at TheCodingCollege.com

At TheCodingCollege.com, we provide comprehensive guides to help you stay ahead with the latest JavaScript features. Whether you’re a beginner or an advanced developer, we’ve got you covered.

Conclusion

ECMAScript 2021 introduces practical features that streamline programming, enhance readability, and improve memory management. Incorporating these updates into your code will make your JavaScript projects more robust and maintainable.

Leave a Comment