Skip to content
jshacks.dev
Fundamentals

What Was New in ES2024 groupBy and Promise.withResolvers

ES2024 added Object.groupBy, Promise.withResolvers, resizable ArrayBuffer, well-formed string methods and the regex v flag. See each with runnable examples.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and npm logos.

Each yearly edition of ECMAScript is small, and the useful ones are the ones you can name a bug for. ES2024, finalized in June 2024, is that kind: a grouping function that replaces the reduce everyone wrote, a promise helper that removes a well-known workaround, buffers that can grow, a safe way to check that a string is valid Unicode, and a regular expression flag that finally does set arithmetic. Every feature below runs on Node.js 24 and in current browsers, and the snippets show output from a real run. This post goes through them in order of how often you will use them, with the old way next to the new. The rest of the recent editions are in what was new in ES2025 and what is new in ES2026, and the whole language is mapped in the guide to modern JavaScript.

Object.groupBy and Map.groupBy

Grouping a list by a key is one of the most written reductions. Two static methods now do it, returning one array per key.

JavaScript
const orders = [
  { id: 1, status: "paid", total: 40 },
  { id: 2, status: "open", total: 15 },
  { id: 3, status: "paid", total: 90 },
  { id: 4, status: "refunded", total: 25 },
];

const byStatus = Object.groupBy(orders, (order) => order.status);
console.log(Object.keys(byStatus));
console.log(byStatus.paid.map((order) => order.id));
console.log(Object.getPrototypeOf(byStatus));

const bySize = Map.groupBy(orders, (order) => (order.total >= 30 ? "large" : "small"));
console.log([...bySize].map(([size, list]) => [size, list.length]));

const byDay = Map.groupBy([1, 2, 3, 4, 5], (n) => (n % 2 === 0 ? true : false));
console.log(byDay.get(true), byDay.get(false));

const legacy = orders.reduce((groups, order) => {
  (groups[order.status] ??= []).push(order.id);
  return groups;
}, {});
console.log(legacy);
Text
[ 'paid', 'open', 'refunded' ]
[ 1, 3 ]
null
[ [ 'large', 2 ], [ 'small', 2 ] ]
[ 2, 4 ] [ 1, 3, 5 ]
{ paid: [ 1, 3 ], open: [ 2 ], refunded: [ 4 ] }

Object.groupBy returned a plain object of arrays whose prototype is null, so keys like constructor cannot collide with inherited names, and it also means byStatus.hasOwnProperty does not exist. Map.groupBy accepts keys of any type, including booleans and objects. The callback receives (item, index). The older reduce, shown last, needed the ??= idiom to start each group, and it is exactly what the new methods replace. The Map result is the better choice when keys are not strings, a trade-off covered in the post on Sets and Maps.

Promise.withResolvers

The usual way to settle a promise from outside its constructor was to capture resolve and reject into outer variables. Promise.withResolvers() returns them with the promise.

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

const task = deferred();
setTimeout(() => task.resolve("finished"), 5);
console.log(await task.promise);

const failing = deferred();
failing.reject(new Error("cancelled"));
console.log(await failing.promise.catch((error) => error.message));

function legacyDeferred() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, reject };
}

const events = [];
const queue = [];

function waitForEvent() {
  const waiter = Promise.withResolvers();
  queue.push(waiter);
  return waiter.promise;
}

const pending = waitForEvent();
queue.shift().resolve("event arrived");
events.push(await pending);
console.log(events, typeof legacyDeferred);
Text
finished
cancelled
[ 'event arrived' ] function

The legacy helper needed two let declarations and a callback that did nothing but copy references out. The new method is one line and the destructured names are the ones you meant. Typical uses are queues of waiters, an event that a later call will settle, a cancellation signal and tests that control when a promise resolves. A promise that is never settled, with no handler on its rejection, is the usual bug to watch for.

Resizable and transferable ArrayBuffer

Buffers could not change size or ownership. ES2024 added both: a buffer can be created with a maximum size, resized in place, and its contents moved to a new buffer with the old one detached.

JavaScript
const buffer = new ArrayBuffer(4, { maxByteLength: 16 });
const view = new Uint8Array(buffer);

console.log(buffer.resizable, buffer.byteLength, buffer.maxByteLength, view.length);

buffer.resize(10);
console.log(buffer.byteLength, view.length);

view.fill(7);
const moved = buffer.transfer(8);
console.log(buffer.detached, buffer.byteLength, moved.byteLength, new Uint8Array(moved));

const fixed = new ArrayBuffer(4).transfer(2);
console.log(fixed.resizable, fixed.byteLength);

try {
  buffer.resize(2);
} catch (error) {
  console.log(error.name);
}
Text
true 4 16 4
10 10
true 0 8 Uint8Array(8) [
  7, 7, 7, 7,
  7, 7, 7, 7
]
false 2
TypeError

A length-tracking view follows the buffer as it grows. transfer(8) produced a new buffer of the requested size holding the old bytes, padded with zeros, and detached the original, which reports zero bytes. Transfer avoids copying when handing memory to a worker, and lets a function take ownership of a buffer it was given. The typed arrays post covers the buffer model.

Well-formed strings

A JavaScript string can contain a lone surrogate, which is not valid Unicode and breaks encoders and some APIs. Two methods detect and repair it.

JavaScript
const good = "café \u{1F600}";
const bad = "oops\ud800";

console.log(good.isWellFormed(), bad.isWellFormed());
console.log(JSON.stringify(bad.toWellFormed()), bad.toWellFormed().length);
console.log(good.toWellFormed() === good);

try {
  encodeURIComponent(bad);
} catch (error) {
  console.log(error.name);
}

console.log(encodeURIComponent(bad.toWellFormed()));
console.log(new TextEncoder().encode(bad).length);
Text
true false
"oops�" 5
true
URIError
oops%EF%BF%BD
7

The check returned false for the string with the lone surrogate, and the repair replaced it with the replacement character, which is encoded as %EF%BF%BD in a URL. A well-formed string is returned as is. Use isWellFormed() at a boundary where text goes to an API that requires valid Unicode, as covered in the post on UTF-16 strings.

The v flag for regular expressions

The v flag extends the u flag with set operations inside character classes, and with properties of strings such as emoji sequences.

JavaScript
const letterNotLower = /[\p{L}--[a-z]]/v;
const greekLetters = /[\p{Script=Greek}&&\p{L}]/v;
const emoji = /^\p{RGI_Emoji}$/v;

console.log(letterNotLower.test("a"), letterNotLower.test("A"), letterNotLower.test("é"));
console.log(greekLetters.test("α"), greekLetters.test("a"));
console.log(emoji.test("😀"), emoji.test("👨‍👩‍👧"), emoji.test("a"));
console.log("Hello Wörld".match(/[\p{L}--[a-z]]/gv));
console.log(/[\q{abc|d}]/v.test("abc"));
Text
false true true
true false
true true false
[ 'H', 'W', 'ö' ]
true

The first pattern matched letters that are not lower-case ASCII: -- is subtraction. The second used &&, intersection, to keep Greek letters only. \p{RGI_Emoji} matches a whole emoji sequence, such as the family, as a unit, where the older flag saw several code points. The \q{...} form matches a string as a class member. The regular expressions primer covers the surrounding syntax.

Atomics.waitAsync

For code that shares memory between threads, Atomics.waitAsync() is a non-blocking version of wait. It returns a promise, so the main thread, which must not block, can wait for another thread to signal.

JavaScript
const shared = new SharedArrayBuffer(4);
const cell = new Int32Array(shared);
const keepAlive = setTimeout(() => {}, 500);

const immediate = Atomics.waitAsync(cell, 0, 1);
console.log(immediate);

const waiting = Atomics.waitAsync(cell, 0, 0, 10);
console.log(waiting.async, await waiting.value);

const woken = Atomics.waitAsync(cell, 0, 0, 1000);
Atomics.notify(cell, 0, 1);
console.log(woken.async, await woken.value);
clearTimeout(keepAlive);
Text
{ async: false, value: 'not-equal' }
true timed-out
true ok

A wait on a value that does not match returns at once with "not-equal" and no promise. A wait on a matching value returns an object whose value is a promise. The timer behind a wait does not keep the Node.js process alive, so the example holds a separate timer open. The first promise resolved to "timed-out" after 10 milliseconds, or to "ok" when another call to Atomics.notify woke it. Most application code never touches shared memory, and the function is aimed at library authors building locks and queues over workers.

Migrating the old patterns

Three habits are worth changing now. Replace grouping reducers with Object.groupBy or Map.groupBy, and keep the callback's return value a string or a primitive, because Object.groupBy converts keys with the same rules as property names. Replace the captured-resolver idiom with Promise.withResolvers(), and keep the rule that every promise you create must eventually settle. And where code branches on typeof buffer.transfer, drop the fallback once your floor reaches Node.js 22. Each change is local, removes boilerplate and is covered by the tests you already have, since the behavior is the same and only the spelling is shorter.

What did not make it

ES2024 is small on purpose. The features above are all that landed as new standard library, and several widely used additions from the same period, such as the non-mutating array methods toSorted(), toReversed() and with(), belong to ES2023. If a feature you expect is missing from an edition, check the proposals repository for its stage: a feature is in a year's edition only if it reached stage 4 before the cutoff. The post on TC39 explains the process.

Where to be careful

Support is the practical question. Everything here runs on Node.js 22 and later and current Chrome, Firefox and Safari, and some of it is a year or two older in engines. Check the engine you must support, and use a polyfill for Object.groupBy and Promise.withResolvers if you cannot raise the floor, since both are easy to write. The regular expression v flag throws a SyntaxError at parse time in an engine that lacks it, which is a deployment failure and not a runtime fallback, so gate it behind a feature check with new RegExp(source, "v") in a try block.

The features are defined in the ECMAScript 2024 specification, and MDN's pages on Object.groupBy and Promise.withResolvers list the support tables.

Also inAsync
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.