What are ES2021 - ES12 features?

1. Logical Assignment Operators

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

let a = null;
let b = 0;
let c = 1;

a ||= 10; // a = 10 (null is falsy)
b &&= 20; // b = 0 (0 is falsy, so no assignment)
c ??= 30; // c = 1 (1 is not null or undefined, so no assignment)

console.log(a, b, c); // 10, 0, 1

2. Numeric Separators

Numeric separators (_) make large numbers more readable by visually separating groups of digits. They don’t affect the number’s value.

You can use _ in integers, floating-point numbers, and BigInts, but not at the start, end, or next to a decimal point.

const billion = 1_000_000_000; // Easier to read
const creditCardNumber = 1234_5678_9012_3456;

console.log(billion); // 1000000000
console.log(creditCardNumber); // 1234567890123456

3. String.prototype.replaceAll()

The replaceAll() method allows replacing all occurrences of a substring or pattern in a string without using regular expressions.

Unlike replace(), which only replaces the first occurrence unless a regex with the global flag is used, replaceAll() replaces all occurrences by default.

const str = "foo bar foo baz";
console.log(str.replaceAll("foo", "qux")); // "qux bar qux baz"

4. Promise.any()

Promise.any() takes an array of promises and returns the first promise that resolves successfully. If all promises reject, it returns an AggregateError.

5. WeakRefs

WeakRefs (Weak References) allow referencing objects without preventing their garbage collection. They are useful for building caches or managing memory-sensitive data.

let obj = { name: "Alice" };
const weakRef = new WeakRef(obj);

console.log(weakRef.deref()); // { name: "Alice" }
obj = null; // obj is eligible for garbage collection
console.log(weakRef.deref()); // undefined (object has been garbage collected)

6. FinalizationRegistry

FinalizationRegistry is used to register a callback that gets executed after an object has been garbage collected. It complements WeakRefs.

Garbage collection timing is not guaranteed, so callbacks might not execute immediately.

const registry = new FinalizationRegistry((value) => {
console.log(`Object with value ${value} has been garbage collected.`);
});

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

obj = null; // When garbage collected, the callback will run