Sub topic 15
Background: Why the Methods Are Static
You have used Object.groupBy and Map.groupBy throughout this tutorial. You may have wondered why they are called as Object.groupBy(items, fn) and not as items.groupBy(fn), the way you call map, filter, and reduce. This chapter explains how the design ended up static and what that choice means for your code.
This chapter assumes you know how array methods are defined on Array.prototype, what a polyfill is, and how for...of consumes iterables. Nothing here changes how you use the methods. It explains why they look the way they do, which helps when you read older blog posts, old TypeScript typings, or code that refers to Array.prototype.group.
The Original Plan: A Prototype Method
The TC39 proposal for array grouping started out the way most people would expect. It added two methods to Array.prototype:
Array.prototype.groupBy(fn)returned an object of groups.Array.prototype.groupByToMap(fn)returned aMapof groups.
That design matched the rest of the array API. You could chain it after filter or map, and it read naturally:
// Hypothetical: this is the early proposal shape, not real JavaScript today.
// inventory.filter((item) => item.quantity > 0).groupBy(({ type }) => type);The proposal moved quickly through the early stages. Then it ran into a problem that has hit several other array additions: existing websites already used those names.
Web Compatibility: The Problem with New Prototype Names
JavaScript has one hard rule for new features: they must not break existing websites. Browsers cannot ship a change that makes popular pages stop working, even when those pages depend on old or unusual code.
Many older libraries add their own methods to built-in prototypes. A common pattern looks like this:
if (!Array.prototype.groupBy) {
Array.prototype.groupBy = function (key) {
// Library-specific behavior, often with a different signature,
// for example taking a property name string instead of a callback.
const out = {};
for (const item of this) {
(out[item[key]] ??= []).push(item);
}
return out;
};
}When the browser has no native groupBy, the library installs its own version and the site works. When the browser ships a native groupBy, the if check skips the library's version. The site now calls the native method with arguments it was never designed for, such as a property name string where a callback is expected. Code that used to work starts throwing errors or returning wrong results.
Other patterns break too. Some libraries copy only enumerable methods from one prototype to another, and native methods are non-enumerable, so the copy silently misses them. Some code relies on a property being absent to tell real arrays apart from custom collections.
This had happened before:
| Proposed name | Conflict | Final name |
|---|---|---|
| `Array.prototype.contains` | Clashed with MooTools, an old library | `Array.prototype.includes` |
| `Array.prototype.flatten` | Clashed with MooTools ("SmooshGate") | `Array.prototype.flat` |
| `Array.prototype.groupBy` | Clashed with code already using the name | Renamed, then moved to static methods |
The Rename, and Then the Move
The committee first renamed the methods to Array.prototype.group and Array.prototype.groupToMap. Browser engines then began testing these names and found that group also conflicted with existing code on real sites.
At that point the committee changed approach. Instead of guessing yet another prototype name, they moved the functions onto the constructors:
Object.groupBy(items, fn)returns a null-prototype object.Map.groupBy(items, fn)returns aMap.
Static methods on Object and Map are much safer to add. Old libraries rarely patch Object.groupBy or Map.groupBy, and adding a property to a constructor does not change how every existing array behaves. The static design reached Stage 4 in 2023 and was published in ES2024.
You can confirm this in any modern browser or Node.js 21 or later:
console.log(typeof Array.prototype.group); // "undefined"
console.log(typeof Array.prototype.groupBy); // "undefined"
console.log(typeof Array.prototype.groupToMap); // "undefined"
console.log(typeof Object.groupBy); // "function"
console.log(typeof Map.groupBy); // "function"What the Static Design Gives You
The move started as a compatibility fix, but it brought several real advantages.
Any Iterable Works
A method on Array.prototype would naturally work on arrays. A static method takes its input as an argument, so it can take any iterable: strings, Sets, Map entries, generator output, and so on. You saw this in the chapter on grouping iterables. Here is a generator example:
function* readings() {
yield { sensor: "a", value: 12 };
yield { sensor: "b", value: 7 };
yield { sensor: "a", value: 15 };
}
const bySensor = Object.groupBy(readings(), ({ sensor }) => sensor);
console.log(bySensor.a.map((r) => r.value)); // [12, 15]With a prototype method, you would first need Array.from(readings()) or [...readings()].
The Namespace Names the Result
groupByToMap was an awkward name. With static methods, the constructor tells you the result type: Object.groupBy builds an object, and Map.groupBy builds a Map. This matches existing static factories like Object.fromEntries and Array.from, which also build a value of their own type from an input.
Arrays Stay Unchanged
No new property appears on every array. Code that loops over array properties with for...in, or checks for a method's presence, behaves the same as before.
The Cost: No Method Chaining
The main downside is that you cannot chain grouping onto the end of an array pipeline. You wrap the pipeline instead:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
];
const inStockByType = Object.groupBy(
inventory.filter((item) => item.quantity > 0),
({ type }) => type
);
console.log(Object.keys(inStockByType)); // ["vegetables", "meat", "fruit"]
console.log(inStockByType.fruit.map((i) => i.name)); // ["cherries"]For long pipelines, an intermediate variable often reads better than deep nesting:
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
];
const inStock = inventory.filter((item) => item.quantity > 0);
const byType = Object.groupBy(inStock, ({ type }) => type);
console.log(Object.keys(byType)); // ["vegetables", "meat"]Gotcha: Do Not Patch the Prototype Yourself
You might be tempted to restore chaining by adding your own Array.prototype.groupBy. Don't. That is the exact pattern that blocked the original proposal. If a future standard ever adds a method with that name, your code becomes the next compatibility problem. It also affects every array in the program, including arrays created by third-party libraries.
A plain helper gives you the same convenience without touching globals:
const groupInStock = (items, keyFn) =>
Object.groupBy(items.filter((item) => item.quantity > 0), keyFn);
const result = groupInStock(
[
{ name: "goat", type: "meat", quantity: 23 },
{ name: "bananas", type: "fruit", quantity: 0 },
],
({ type }) => type
);
console.log(Object.keys(result)); // ["meat"]Gotcha: Iterable, Not Array-Like
Because the static methods consume their input with the iteration protocol, they need a real iterable. An array-like object such as { length: 2, 0: "a", 1: "b" } has no Symbol.iterator, so it throws:
const arrayLike = { length: 2, 0: "a", 1: "b" };
try {
Object.groupBy(arrayLike, (x) => x);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const grouped = Object.groupBy(Array.from(arrayLike), (x) => x);
console.log(Object.keys(grouped)); // ["a", "b"]Convert array-likes with Array.from first. A prototype method would have had the same requirement in practice, but the error is easier to hit here because the input is an argument and nothing stops you from passing a non-iterable.
Exercise
A library you maintain contains if (!Array.prototype.group) { Array.prototype.group = function (prop) { /* groups by a property name string */ }; }. Explain why code like this caused trouble for the original proposal, and why it is harmless to the current Object.groupBy.
Show answer
If browsers had shipped a native Array.prototype.group, the if check would skip the library's version. Callers that pass a property name string would then reach the native method, which expects a callback, so they would get a TypeError or wrong results. The current standard puts grouping on Object and Map and never defines Array.prototype.group, so the library's patch still installs and behaves as before. It is still poor practice, though, because a future standard could claim the name.
Exercise
Rewrite orders.filter((o) => o.paid).groupBy((o) => o.region) so it works in current JavaScript and returns a Map instead of an object.
Show answer
Map.groupBy(orders.filter((o) => o.paid), (o) => o.region). The filtered array becomes the first argument to the static method, and Map.groupBy takes the place of the old groupByToMap.
Exercise
Name two advantages the static design has over the original prototype design, apart from avoiding name clashes.
Show answer
The static methods accept any iterable (strings, Sets, generators) without converting it to an array first. The constructor name states the result type (Object or Map), so no awkward suffix like ToMap is needed. A third valid answer is that no new property is added to every array.