Sub topic 4
Inherited Properties and Filtering with Object.hasOwn
This chapter assumes you know how for...in produces string keys and what makes a property enumerable. It also assumes you have a rough idea that objects link to other objects through a prototype. The prototype detail that matters here is that for...in does not stop at the object you hand it. It walks up the whole prototype chain and reports every enumerable key it finds along the way. That surprises most people the first time, and it is the source of a long-standing family of bugs.
How for...in Walks the Prototype Chain
Every object has an internal link to another object, its prototype, or to null. When you read obj.x and obj has no own property x, JavaScript looks at the prototype, then at the prototype's prototype, and so on. for...in follows the same chain. It visits the object's own enumerable string keys first, then the enumerable string keys of each prototype in turn.
const animal = { breathes: true };
const dog = Object.create(animal);
dog.barks = true;
const puppy = Object.create(dog);
puppy.name = 'Rex';
for (const key in puppy) {
console.log(key);
}
// name
// barks
// breathespuppy owns only name, but the loop reports three keys, because barks lives on dog and breathes lives on animal.
Why you rarely see built-in methods
Object.prototype holds toString, hasOwnProperty and others. They never show up in for...in because they are non-enumerable. The same goes for class methods: methods defined in a class body are placed on the prototype as non-enumerable properties.
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, ${this.name}`;
}
}
const u = new User('Ada');
for (const key in u) {
console.log(key);
}
// nameMethods added the old way, by assigning to prototype, are enumerable. They will appear:
function Legacy(name) {
this.name = name;
}
Legacy.prototype.greet = function () {
return 'hi';
};
for (const key in new Legacy('Alan')) {
console.log(key);
}
// name
// greetPre-ES2015 code, polyfills and some libraries use exactly this pattern, so inherited keys turn up in real programs more often than you might expect.
Shadowing: each key appears once
If an object and its prototype both have a property with the same name, for...in reports that name once, using the nearest one. A key counts as "already seen" even when the own property that shadows it is non-enumerable. In that case the name is hidden completely:
const proto = { a: 1, b: 2 };
const obj = Object.create(proto);
obj.a = 10;
Object.defineProperty(obj, 'b', { value: 20, enumerable: false });
for (const key in obj) {
console.log(key, obj[key]);
}
// a 10a comes out once with the own value. b does not come out at all, because the own non-enumerable b shadows the enumerable one on proto.
Filtering with Object.hasOwn
Most of the time you only want the object's own data. The standard fix is to skip any key that is not an own property:
const defaults = { theme: 'light' };
const settings = Object.create(defaults);
settings.fontSize = 14;
for (const key in settings) {
if (!Object.hasOwn(settings, key)) continue;
console.log(key, settings[key]);
}
// fontSize 14Object.hasOwn(obj, key) returns true only when key is a property directly on obj, whether or not it is enumerable. It arrived in ES2022 and works in all current browsers and in Node.js 16.9 and later.
Why not obj.hasOwnProperty(key)?
Older code calls the method inherited from Object.prototype. That works until it doesn't, and it breaks in two ways.
// 1. Objects with no prototype have no such method
const dict = Object.create(null);
dict.apple = 3;
// dict.hasOwnProperty('apple'); // TypeError: dict.hasOwnProperty is not a function
console.log(Object.hasOwn(dict, 'apple')); // true
// 2. The method can be shadowed by data
const record = { hasOwnProperty: 'yes', id: 7 };
// record.hasOwnProperty('id'); // TypeError: record.hasOwnProperty is not a function
console.log(Object.hasOwn(record, 'id')); // trueObject.create(null) is a common way to build a lookup table with no inherited keys, and parsed JSON can contain any key name, hasOwnProperty included. Object.hasOwn is a static function that never looks anything up on the object itself, so neither case can break it. Before ES2022, the safe form was Object.prototype.hasOwnProperty.call(obj, key). You will still find it in older codebases, and it behaves the same way.
Comparing the membership checks
| Check | Own properties | Inherited properties | Non-enumerable | Safe on `Object.create(null)` |
|---|---|---|---|---|
| `key in obj` | yes | yes | yes | yes |
| `obj.hasOwnProperty(key)` | yes | no | yes | no |
| `Object.hasOwn(obj, key)` | yes | no | yes | yes |
| `Object.keys(obj).includes(key)` | yes | no | no | yes |
The in operator and the for...in loop share a keyword, but they answer different questions. in tells you whether a key can be reached anywhere on the chain, enumerable or not. for...in lists only the enumerable keys on that chain.
Prototype Pollution: When Every Loop Changes
Inherited keys get dangerous when someone adds an enumerable property to Object.prototype. That one change affects every unfiltered for...in loop over an ordinary object in the whole program:
Object.prototype.injected = 'surprise';
const config = { port: 8080 };
for (const key in config) {
console.log(key);
}
// port
// injected
for (const key in config) {
if (Object.hasOwn(config, key)) console.log(key);
}
// port
delete Object.prototype.injected; // clean upThis can happen through a careless polyfill. It can also happen through a prototype-pollution vulnerability, where untrusted input such as {"__proto__": {"isAdmin": true}} is deep-merged into an object. Code that copies or checks fields with an unfiltered for...in then picks up attacker-controlled keys. Filtering with Object.hasOwn is cheap protection against this.
Common Errors
- Filtering against the wrong object. In nested loops, write
Object.hasOwn(inner, key)and notObject.hasOwn(outer, key). The bug runs quietly and just drops or keeps the wrong keys. - Assuming the filter catches non-enumerable own keys. It cannot.
for...innever yields them in the first place, so the filter never sees them. - Expecting own keys to be enough when you need defaults. When the prototype holds fallback values on purpose, as
defaultsdoes above, filtering hides them. Decide whether you want "what this object stores" or "what this object resolves to." - Using
into filter.if (key in obj)is always true insidefor...in, so it filters nothing.
Exercise
Given const base = { a: 1 }; const child = Object.create(base); child.b = 2; Object.defineProperty(child, 'c', { value: 3, enumerable: false });, which keys does for (const k in child) log, and which of them pass Object.hasOwn(child, k)?
Show answer
The loop logs b then a. c is skipped because it is non-enumerable. b passes the filter. a fails it because it is inherited from base. Called directly, Object.hasOwn(child, 'c') would return true, but the loop never yields c.
Exercise
A function counts fields with for (const k in obj) if (obj.hasOwnProperty(k)) count++;. It crashes when given the result of JSON.parse('{"hasOwnProperty": 1, "x": 2}'). Why, and what is the fix?
Show answer
The parsed object has an own property named hasOwnProperty whose value is the number 1. That property shadows the inherited method, so obj.hasOwnProperty(k) throws "not a function". Replace the call with Object.hasOwn(obj, k), which does not look anything up on obj.
Exercise
Why does a class instance's for...in loop not list its methods, while an object built from a constructor function with Ctor.prototype.method = function () {} does?
Show answer
Methods defined in a class body are created as non-enumerable properties on the prototype. A method assigned directly to Ctor.prototype is an ordinary enumerable property, so for...in reaches it through the prototype chain.