Sub topic 5
Working with a Null-Prototype Result
This chapter assumes you have already called Object.groupBy with a key callback. You should also know how plain objects inherit methods from Object.prototype, and how optional chaining (?.) and nullish coalescing (??) work. The topic here is one detail of the result that catches people out. The object returned by Object.groupBy has no prototype at all.
What "null prototype" means
Most objects you write, such as {}, are linked to Object.prototype. That link is why {}.toString(), {}.hasOwnProperty("x") and "constructor" in {} all work even though you never defined those members. When JavaScript looks up a property and can't find it on the object itself, it follows the prototype chain upward.
Object.groupBy creates its result as if with Object.create(null). The chain stops immediately. The only properties on the object are the group keys your callback returned.
const groups = Object.groupBy(["apple", "avocado", "banana"], (w) => w[0]);
console.log(Object.getPrototypeOf(groups)); // null
console.log(groups); // [Object: null prototype] { a: [ 'apple', 'avocado' ], b: [ 'banana' ] }
console.log(typeof groups.toString); // "undefined"
console.log(typeof groups.hasOwnProperty); // "undefined"Node.js and browser consoles mark these objects with a label like [Object: null prototype]. When you see that label, you know that inherited methods are missing.
Why groupBy works this way
Group keys come from your data, and data can contain any string. If the result inherited from Object.prototype, keys such as "constructor", "toString" or "__proto__" would collide with inherited members. The classic reduce pattern shows the problem:
const words = ["constructor", "toString", "map"];
try {
const byWord = words.reduce((acc, w) => {
(acc[w] ??= []).push(w);
return acc;
}, {});
console.log(byWord);
} catch (e) {
console.log(e.constructor.name); // "TypeError"
}
const safe = Object.groupBy(words, (w) => w);
console.log(Object.keys(safe)); // ["constructor", "toString", "map"]
console.log(safe.constructor); // ["constructor"]In the reduce version, acc["constructor"] already holds the inherited Object function. That value is not nullish, so ??= leaves it alone, and calling .push on a function throws. Object.groupBy has no inherited members, so every key starts out empty and the bug can't happen.
The null prototype is a deliberate safety feature. The cost is that a few habits you use with ordinary objects no longer work.
What breaks and what still works
| Operation | Works on the result? | Notes |
|---|---|---|
| `groups.key`, `groups[key]` | Yes | Reads own properties normally |
| `Object.keys`, `Object.values`, `Object.entries` | Yes | Static methods don't need a prototype |
| `for...in`, `for...of Object.entries(...)` | Yes | No inherited keys to filter out |
| Spread `{ ...groups }` | Yes | Produces an ordinary object |
| `JSON.stringify(groups)` | Yes | Serializes own properties |
| `Object.hasOwn(groups, key)` | Yes | Recommended existence check |
| `key in groups` | Yes | Safe here because nothing is inherited |
| `groups.hasOwnProperty(key)` | No | Throws `TypeError`, method is missing |
| `String(groups)`, `` `${groups}` ``, `"" + groups` | No | Throws `TypeError` because there is no `toString` or `valueOf` |
| `assert.deepStrictEqual(groups, {...})` | No | Prototypes differ (`null` versus `Object.prototype`) |
The string-conversion failure is easy to hit by accident in log messages:
const groups = Object.groupBy([1, 2, 3], (n) => (n % 2 ? "odd" : "even"));
try {
console.log(`Groups: ${groups}`);
} catch (e) {
console.log(e.constructor.name, "-", e.message);
// TypeError - Cannot convert object to primitive value
}
console.log("Groups:", groups); // passing as a separate argument is fine
console.log(`Groups: ${JSON.stringify(groups)}`); // Groups: {"odd":[1,3],"even":[2]}Note that a plain object in a template literal doesn't throw. It prints the useless [object Object]. So this error is specific to null-prototype objects, and it can surprise you in code that used to work with a reduce-built result.
Checking whether a group exists
When your callback never produces a key, that group simply isn't there. Reading it gives undefined, not an empty array. Here are the safe ways to check and read:
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 byType = Object.groupBy(inventory, ({ type }) => type);
// Existence checks
console.log(Object.hasOwn(byType, "fruit")); // true
console.log("fruit" in byType); // true
console.log("toString" in byType); // false (would be true on a plain object)
console.log(Object.prototype.hasOwnProperty.call(byType, "meat")); // true
// Reading a group that may be missing
console.log(byType.dairy?.length ?? 0); // 0
const dairyNames = (byType.dairy ?? []).map((item) => item.name);
console.log(dairyNames); // []Object.hasOwn (ES2022) is the clearest choice and works on any object, whatever its prototype. The in operator is also correct for this result, because nothing is inherited. Avoid using in on plain objects built by hand, where "toString" in obj returns true. Object.prototype.hasOwnProperty.call(...) is the older spelling. Use it only if you must support runtimes from before Object.hasOwn, and remember that those runtimes won't have Object.groupBy either.
Converting to an ordinary object
Sometimes you need a normal object. A library may call obj.hasOwnProperty, a test may compare prototypes, or a template engine may stringify values. There are two safe conversions:
const groups = Object.groupBy([1, 2, 3], (n) => (n % 2 ? "odd" : "even"));
const viaSpread = { ...groups };
const viaEntries = Object.fromEntries(Object.entries(groups));
console.log(Object.getPrototypeOf(viaSpread) === Object.prototype); // true
console.log(viaEntries.hasOwnProperty("odd")); // trueBoth create a shallow copy. The group arrays themselves are shared with the original result, not copied.
Edge case: the `__proto__` key
The conversion method matters when a key is "__proto__". On the null-prototype result, "__proto__" is an ordinary own property. No inherited accessor gives it special meaning. Spread and Object.fromEntries define properties directly, so they keep it. Object.assign writes with normal assignment. Assigning to __proto__ on a plain object runs the inherited setter, which replaces the prototype instead of storing the data.
const tricky = Object.groupBy(["x", "y"], (s) =>
s === "x" ? "__proto__" : "other"
);
console.log(Object.keys(tricky)); // ["__proto__", "other"]
console.log(tricky.__proto__); // ["x"] (own data, not a prototype)
const spread = { ...tricky };
console.log(Object.hasOwn(spread, "__proto__")); // true
const assigned = Object.assign({}, tricky);
console.log(Object.hasOwn(assigned, "__proto__")); // false
console.log(Array.isArray(Object.getPrototypeOf(assigned))); // trueWith Object.assign, the group disappears and the copy's prototype is now an array. If any of your keys come from user input, convert with spread or Object.fromEntries, and don't use Object.assign.
Null prototypes in tests
Node's strict deep-equality check compares prototypes, so a null-prototype result does not equal an object literal with the same contents:
const assert = require("node:assert/strict");
const groups = Object.groupBy([1, 2, 3], (n) => (n % 2 ? "odd" : "even"));
try {
assert.deepStrictEqual(groups, { odd: [1, 3], even: [2] });
} catch (e) {
console.log("fails:", e.code); // fails: ERR_ASSERTION
}
assert.deepStrictEqual({ ...groups }, { odd: [1, 3], even: [2] });
console.log("passes");Run this as a CommonJS file, for example node check.cjs. Some other test libraries also compare prototypes in their strict matchers. Spreading the result into a literal before comparing is the simplest fix, and it states what you really mean: the keys and groups match.
Exercise
A teammate writes if (groups.hasOwnProperty("admin")) { notify(groups.admin); } after calling Object.groupBy(users, (u) => u.role). What happens, and how would you rewrite the check?
Show answer
groups has a null prototype, so groups.hasOwnProperty is undefined, and calling it throws TypeError: groups.hasOwnProperty is not a function. Rewrite it as if (Object.hasOwn(groups, "admin")) { ... } or if ("admin" in groups) { ... }. Either is correct because the result inherits nothing.
Exercise
Given const g = Object.groupBy(["a", "b"], (s) => (s === "a" ? "__proto__" : "x"));, what do Object.keys({ ...g }) and Object.keys(Object.assign({}, g)) print, and why do they differ?
Show answer
Object.keys({ ...g }) prints ["__proto__", "x"], because spread defines own properties directly. Object.keys(Object.assign({}, g)) prints ["x"], because Object.assign assigns target.__proto__ = ["a"]. That assignment runs the inherited setter on the plain target and changes its prototype instead of creating a property.
Exercise
Write one expression that returns the number of items in the "restock" group of a byStock result, or 0 if that group does not exist.
Show answer
byStock.restock?.length ?? 0. Optional chaining returns undefined when the group is missing, and ?? 0 turns that into 0. An equivalent form is (byStock.restock ?? []).length.