Modern JavaScript you can use now: iterator helpers, Set methods and more

By

Published Updated 2 min read

Several long-awaited additions are now widely available. Here are the ones that remove the most boilerplate. Verify support for your audience on MDN or caniuse before shipping.

Iterator helpers

Iterators finally have map, filter, take and toArray. They are lazy, so only the work you need is done.

JavaScript
function* ids() {
  let id = 1;
  while (true) yield id++;
}


const firstEvenSquares = ids()
  .filter((n) => n % 2 === 0)
  .map((n) => n * n)
  .take(3)
  .toArray();


console.log(firstEvenSquares); // [4, 16, 36]

Before, this required converting to an array (impossible for an infinite generator) or writing a manual loop.

Set methods

Set gained real set algebra.

JavaScript
const frontend = new Set(['ann', 'bob', 'cleo']);
const onCall = new Set(['bob', 'dan']);


frontend.intersection(onCall);        // Set { 'bob' }
frontend.union(onCall);               // ann, bob, cleo, dan
frontend.difference(onCall);          // ann, cleo
frontend.isSubsetOf(onCall);          // false

Object.groupBy and Map.groupBy

JavaScript
const orders = [
  { id: 1, status: 'paid' },
  { id: 2, status: 'pending' },
  { id: 3, status: 'paid' },
];


const byStatus = Object.groupBy(orders, (order) => order.status);
// { paid: [ {id:1}, {id:3} ], pending: [ {id:2} ] }

Promise.withResolvers and Promise.try

Promise.withResolvers() removes the "extract resolve out of the constructor" pattern:

JavaScript
const { promise, resolve, reject } = Promise.withResolvers();


socket.addEventListener('open', () => resolve(socket), { once: true });
socket.addEventListener('error', reject, { once: true });


await promise;

Promise.try turns a function that may throw synchronously or return a promise into a single promise chain:

JavaScript
Promise.try(() => parseConfig(input))
  .then(applyConfig)
  .catch(reportError);

RegExp.escape

Safely embed user input in a regular expression:

JavaScript
const query = '1+1=2 (really?)';
const re = new RegExp(RegExp.escape(query), 'i');

TypeScript

Set the lib (or target) to es2025 so these APIs are typed. TypeScript 6.0 does this by default.

Takeaway

None of these are flashy, but together they replace a lot of utility code and small helper libraries. Adopt them where your browser support policy allows.

Sources and further reading