ES12 APIs & Features

ES12 (ECMAScript 2021) introduced String.prototype.replaceAll, Promise.any, logical assignment operators, and numeric separators.

Released: June 2021
Modern JavaScript
ECMAScript

Other JavaScript Versions

Release Information

Release Date:

June 2021

Version Type:
Modern

Quick Summary

ES12 (ECMAScript 2021) introduced String.prototype.replaceAll, Promise.any, logical assignment operators, and numeric separators.

Top Features

  • String.prototype.replaceAll
  • Promise.any
  • Logical Assignment Operators (??=, &&=, ||=)
  • Numeric Separators (_)
  • WeakRef and FinalizationRegistry

Playground

Try out JavaScript code examples and experiment with features in the official TypeScript playground.

Open JavaScript Playground

API Examples

String.prototype.replaceAll

Returns a new string with all matches of a pattern replaced by a replacement.

const str = "hello world hello";
const newStr = str.replaceAll("hello", "hi");
console.log(newStr); // "hi world hi"

// With regex
const str2 = "hello world hello";
const newStr2 = str2.replaceAll(/hello/g, "hi");
console.log(newStr2); // "hi world hi"

Promise.any

Returns a promise that is fulfilled by the first given promise to be fulfilled.

const promises = [
  Promise.reject("error1"),
  Promise.resolve("success"),
  Promise.reject("error2")
];

Promise.any(promises).then(result => {
  console.log(result); // "success"
});

// If all promises reject
Promise.any([Promise.reject("error")])
  .catch(error => {
    console.log(error); // AggregateError: All promises were rejected
  });

Logical Assignment Operators

Combine logical operators with assignment operators.

let x = 1;
let y = null;
let z = false;

// Nullish coalescing assignment
x ??= 2; // x = 1 (not null/undefined)
y ??= 2; // y = 2

// Logical AND assignment
z &&= true; // z = false (falsy)
x &&= 3; // x = 3 (truthy)

// Logical OR assignment
let a = 0;
a ||= 5; // a = 5 (falsy)
let b = 1;
b ||= 5; // b = 1 (truthy)

Numeric Separators

Use underscores as separators in numeric literals for better readability.

const million = 1_000_000;
const billion = 1_000_000_000;
const pi = 3.141_592_653_589_793;

console.log(million); // 1000000
console.log(billion); // 1000000000
console.log(pi); // 3.141592653589793

// Works with different bases
const binary = 0b1010_0001_1000_0101;
const hex = 0xA0_B0_C0;