ARTICLE AD BOX
I've been diving into the JS Object API, trying to learn it a bit more, and I found something I did not really expect for how groupBy() functions. Here's a little example:
const people = [
{ name: "Ana", role: "dev" },
{ name: "Ben", role: "dev" },
{ name: "Cara", role: "pm" },
];
const grouped = Object.groupBy(people, (person) => person.role);
console.log(grouped);
// seems fine
console.log(grouped.hasOwnProperty("dev"));
// TypeError: grouped.hasOwnProperty is not a function
I naturally assumed that grouped.hasOwnProperty("dev") would be just a normal object, but I was surprised to see that hasOwnProperty is missing.
What is the idea behind the design choice with this? I know it's probably caused by it not inheriting from Object.prototype, but in the case of groupBy(), why would this be considered a better implementation than to have it inherit from Object.prototype?
3

Consider what happens when you have { name: "Weird", role: "hasOwnProperty" }.
2026-03-11 06:14:50 +00:00
Commented 1 hour ago
@VLAZ normally you can still override hasOwnProperty though, right (for example: ({}).hasOwnProperty = { name: "Weird", role: "hasOwnProperty" })? So I guess to that point I'm trying to figure out why we shouldn't inherit from Object.prototype as a default, like an object typically is, if either way it's still overridden by setting hasOwnProperty to a different value, so what's the difference?
2026-03-11 06:25:31 +00:00
Commented 1 hour ago
Yes, you can still override it. But in this case you wouldn't explicitly do it. It would happen implicitly. So, even if we assume the result from groupBy inherited from the object prototype, then your code from the question would still fail. You wouldn't be able to do grouped.hasOwnProperty("dev"). So, you'd have to explain to me why it'd be a good idea for the code to work unreliably and fail randomly with extremely hard to find bugs.
2026-03-11 07:51:35 +00:00
Commented 8 mins ago