Get own and inherited property names in JavaScript
Intermediate · 3 min read
An object in JavaScript can answer to more names than it holds. A Bus object might own seats and wheels, yet also respond to board() and move(), because it borrows them from its class and from the class that class extends. Debugging tools, form builders and "copy every field" helpers often need the full list.
In this tutorial you will collect every property name an object responds to, its own and the inherited ones, without listing any name twice. You will walk the prototype chain, use a Set, and see why the shortcut for...in misses things. You need to know classes and arrays.
The prototype chain
Every object has a hidden link to another object, its prototype. When you read a property the object doesn't have, JavaScript looks in the prototype, then in that object's prototype, and so on. That line of objects is the prototype chain. It ends at null.
Object.getPrototypeOf(obj) returns the next link:
const plain = {};
console.log(Object.getPrototypeOf(plain) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null
Object.prototype is where every ordinary object gets toString, hasOwnProperty and friends.
Classes build chains for you
With class Bus extends Vehicle, a bus object's chain is: the bus itself, then Bus.prototype (where Bus methods live), then Vehicle.prototype, then Object.prototype, then null.
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
13 Own and inherited property names
fairCollect every property name an object responds to, its own and the ones it inherits, without listing anything twice.
Stuck? Three hints, smallest first
- 1. Walk the prototype chain with
Object.getPrototypeOfuntil it returnsnull. - 2. A
Sethandles the de-duplication when a subclass shadows a parent property. - 3.
for...inis a shortcut, but it only sees enumerable properties.
Step 1: set up two classes
class Vehicle {
constructor() { this.wheels = 4; }
move() {}
}
class Bus extends Vehicle {
constructor() { super(); this.seats = 14; }
board() {}
move() {}
}
const bus = new Bus();
console.log(Object.getOwnPropertyNames(bus)); // [ 'wheels', 'seats' ]
super() runs the Vehicle constructor, which sets wheels on the new bus. So both wheels and seats are own properties. Object.getOwnPropertyNames lists only those. Bus also has its own move, which hides, or shadows, the one in Vehicle.
Step 2: walk the chain
A for loop can follow the links: start at the object, step with Object.getPrototypeOf, stop at null:
for (let o = bus; o !== null; o = Object.getPrototypeOf(o)) {
console.log(Object.getOwnPropertyNames(o).length);
}
It prints one number per link: 2 for the bus, 3 for Bus.prototype (constructor, board, move), 2 for Vehicle.prototype (constructor, move), and a bigger number for Object.prototype. Four links, then the loop stops.
Step 3: collect names with a Set
constructor and move appear on two links. A Set keeps each value once, no matter how often you add it:
function allPropertyNames(obj) {
const found = new Set();
for (let o = obj; o !== null; o = Object.getPrototypeOf(o)) {
for (const key of Object.getOwnPropertyNames(o)) found.add(key);
}
return [...found];
}
console.log(allPropertyNames(bus).includes('toString')); // true
console.log(allPropertyNames(bus).filter((k) => k === 'move').length); // 1
[...found] turns the Set back into an array. move appears once, even though two classes define it.
Step 4: stop before Object.prototype
The full walk is correct but noisy: every answer ends with toString, valueOf, hasOwnProperty and more. Usually you only care about your own classes, so stop one link early:
function ownAndInherited(obj) {
const found = new Set();
for (let o = obj; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
for (const key of Object.getOwnPropertyNames(o)) found.add(key);
}
return [...found];
}
console.log(ownAndInherited(bus)); // [ 'wheels', 'seats', 'constructor', 'board', 'move' ]
The o && part also stops the loop at null, in case the object has no Object.prototype in its chain at all.
Step 5: why not just use for...in?
for...in also visits inherited properties, so it looks like a shortcut:
function enumerableNames(obj) {
const keys = [];
for (const key in obj) keys.push(key);
return keys;
}
console.log(enumerableNames(bus)); // [ 'wheels', 'seats' ]
It misses board and move. for...in only sees enumerable properties, the ones marked to show up in lists, and class methods are non-enumerable on purpose. You can check the setting with Object.getOwnPropertyDescriptor:
console.log(Object.getOwnPropertyDescriptor(Bus.prototype, 'board').enumerable); // false
console.log(Object.getOwnPropertyDescriptor({ go() {} }, 'go').enumerable); // true
A method written in an object literal is enumerable, so for...in behaves differently for the two, even though they look alike.
Step 6: an object with no prototype
Object.create(null) makes an object whose chain is empty from the start:
const bare = Object.assign(Object.create(null), { a: 1 });
console.log(allPropertyNames(bare)); // [ 'a' ]
The loop runs once and stops, because the next link is already null.
The full solution
The panel defines both walks and the for...in version, then prints what each finds for a Bus, how many names the full walk reaches, and that move appears only once. Press Run to compare.
function allPropertyNames(obj) {
const found = new Set();
for (let o = obj; o !== null; o = Object.getPrototypeOf(o)) {
for (const key of Object.getOwnPropertyNames(o)) found.add(key);
}
return [...found];
}
// Stopping before Object.prototype, which is usually the useful version:
// otherwise every answer ends in toString, valueOf, hasOwnProperty...
function ownAndInherited(obj) {
const found = new Set();
for (let o = obj; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
for (const key of Object.getOwnPropertyNames(o)) found.add(key);
}
return [...found];
}
// for...in: inherited, but enumerable only.
function enumerableNames(obj) {
const keys = [];
for (const key in obj) keys.push(key);
return keys;
}
class Vehicle {
constructor() { this.wheels = 4; }
move() {}
}
class Bus extends Vehicle {
constructor() { super(); this.seats = 14; }
board() {}
move() {} // shadows Vehicle.move
}
const bus = new Bus();
console.log('own only :', Object.getOwnPropertyNames(bus));
console.log('own and inherited :', ownAndInherited(bus));
console.log('for...in :', enumerableNames(bus), '<- class methods are not enumerable');
console.log('all the way up :', allPropertyNames(bus).length, 'names, ending at Object.prototype');
console.log('includes toString? :', allPropertyNames(bus).includes('toString'));
console.log('move appears once? :', ownAndInherited(bus).filter((k) => k === 'move').length, '<- shadowed, not duplicated');
Output
15 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('own properties come from the constructor', Object.getOwnPropertyNames(bus).sort(), ['seats', 'wheels']);
test('the walk finds the subclass method', ownAndInherited(bus).includes('board'), true);
test('and the parent method', ownAndInherited(bus).includes('move'), true);
test('a shadowed name appears only once', ownAndInherited(bus).filter((k) => k === 'move').length, 1);
test('own data properties are included', ownAndInherited(bus).includes('seats'), true);
test('and the inherited one', ownAndInherited(bus).includes('wheels'), true);
test('the short walk stops before Object.prototype', ownAndInherited(bus).includes('toString'), false);
test('the full walk reaches it', allPropertyNames(bus).includes('toString'), true);
test('and hasOwnProperty', allPropertyNames(bus).includes('hasOwnProperty'), true);
test('so the full walk is longer', allPropertyNames(bus).length > ownAndInherited(bus).length, true);
test('for...in sees only the data properties here', enumerableNames(bus).sort(), ['seats', 'wheels']);
test('because class methods are non-enumerable', Object.getOwnPropertyDescriptor(Bus.prototype, 'board').enumerable, false);
test('an object-literal method IS enumerable', Object.getOwnPropertyDescriptor({ go() {} }, 'go').enumerable, true);
test('the walk over a plain literal finds its keys', ownAndInherited({ a: 1, b: 2 }).sort(), ['a', 'b']);
test('a prototype-less object has only its own', allPropertyNames(Object.assign(Object.create(null), { a: 1 })), ['a']);
The chain walk is straightforward; the trap is for...in, which people reach for instead. It does traverse inherited properties, but only enumerable ones — and class methods are non-enumerable by design. The assertions show the consequence: for...in on a Bus finds seats and wheels and misses board and move entirely. Methods defined in an object literal are enumerable, so the two cases behave differently for no reason you can see at the call site.
Stopping the walk at Object.prototype is almost always what you want, otherwise every result is padded with toString, valueOf and friends.
Common mistakes
- Using
for...into find methods. Class methods are non-enumerable, so it skips them. - Using an array instead of a Set. Shadowed names like
moveandconstructorshow up twice. - Walking all the way to
nullwhen you didn't mean to. You get everyObject.prototypemethod in the list.
Try it yourself
- Add
class Minibus extends Buswith ahonk()method and list a minibus's names withownAndInherited. - Count how many names the full walk finds on
Object.prototypealone. - Change
ownAndInheritedto return only names that hold functions.