Sub topic 8
Own Properties versus Inherited Properties
This chapter assumes you already know how property lookup walks the prototype chain and how Object.create sets a prototype. Both were covered earlier in the tutorial. You should also be comfortable with object literals and running code in Node.js or a browser console.
A property read like obj.x does not show where x came from. The value might live on obj itself, which makes it an own property. It might also live somewhere up the chain, which makes it an inherited property. Many everyday operations treat these two kinds differently, including copying, serializing, iterating, and validating input. If you don't know which tool checks which kind, you get subtle bugs.
The Core Distinction
An own property is stored directly on the object. An inherited property is found only because lookup continued into a prototype.
const base = {
kind: 'base',
describe() {
return `I am ${this.kind}`;
}
};
const item = Object.create(base);
item.id = 42;
item.kind = 'item'; // own property that shadows base.kind
console.log(item.describe()); // "I am item"
console.log(Object.hasOwn(item, 'id')); // true
console.log(Object.hasOwn(item, 'kind')); // true
console.log(Object.hasOwn(item, 'describe')); // false
console.log('describe' in item); // true
console.log('toString' in item); // true (from Object.prototype)
console.log(Object.hasOwn(base, 'kind')); // true (base still has its own kind)Object.hasOwn(obj, key) (ES2022) looks only at the object itself. The in operator runs the full lookup, so it reports true for anything reachable on the chain, including built-ins like toString.
Choosing the Right Check
Comparing against undefined is the weakest check. A property can exist and hold undefined, and a missing property also reads as undefined:
const settings = Object.create({ theme: 'dark' });
settings.timeout = undefined;
console.log(settings.timeout === undefined); // true
console.log(settings.missing === undefined); // true, indistinguishable
console.log(Object.hasOwn(settings, 'timeout')); // true
console.log(Object.hasOwn(settings, 'missing')); // false
console.log('theme' in settings); // true
console.log(Object.hasOwn(settings, 'theme')); // falseWhy Object.hasOwn Replaced hasOwnProperty
Older code uses obj.hasOwnProperty(key). That is itself an inherited method from Object.prototype, so it can fail in two ways.
// 1. An own property can shadow it
const weird = {
hasOwnProperty() {
return true;
}
};
console.log(weird.hasOwnProperty('nope')); // true (wrong answer)
console.log(Object.hasOwn(weird, 'nope')); // false
// 2. Null-prototype objects do not inherit it at all
const bare = Object.create(null);
bare.x = 1;
try {
bare.hasOwnProperty('x');
} catch (err) {
console.log(err instanceof TypeError); // true
}
// Workarounds
console.log(Object.prototype.hasOwnProperty.call(bare, 'x')); // true (pre-ES2022 idiom)
console.log(Object.hasOwn(bare, 'x')); // trueIteration: for...in Walks the Chain
for...in visits every enumerable string-keyed property, both own and inherited. It lists own keys first, then moves up the chain. If an own property shadows a key further up, that key appears only once.
const base = {
kind: 'base',
describe() {
return `I am ${this.kind}`;
}
};
const item = Object.create(base);
item.id = 42;
item.kind = 'item';
for (const key in item) {
console.log(key, Object.hasOwn(item, key));
}
// id true
// kind true
// describe false
console.log(Object.keys(item)); // ['id', 'kind']
console.log(Object.entries(item)); // [['id', 42], ['kind', 'item']]describe shows up because methods written in an object literal are enumerable. toString and the other Object.prototype methods are non-enumerable, so they never show up. This is why the classic for...in loop includes a guard:
for (const key in item) {
if (!Object.hasOwn(item, key)) continue;
// process own keys only
}In most cases you can use Object.keys, Object.values, or Object.entries with for...of and skip the guard entirely.
Enumerability and Symbols Add Two More Dimensions
"Own" is one axis. Two more axes decide whether a property gets listed: whether it is enumerable, and whether its key is a string or a symbol.
const sym = Symbol('meta');
const obj = Object.create({ inherited: 1 });
obj.visible = 1;
Object.defineProperty(obj, 'hidden', { value: 2, enumerable: false });
obj[sym] = 3;
console.log(Object.keys(obj)); // ['visible']
console.log(Object.getOwnPropertyNames(obj)); // ['visible', 'hidden']
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(meta)]
console.log(Reflect.ownKeys(obj)); // ['visible', 'hidden', Symbol(meta)]
for (const k in obj) console.log(k); // visible, inherited
console.log(Object.hasOwn(obj, 'hidden')); // true
console.log(Object.hasOwn(obj, sym)); // true| Tool | Own | Inherited | Non-enumerable | Symbol keys |
|---|---|---|---|---|
| `key in obj` | yes | yes | yes | yes |
| `Object.hasOwn(obj, key)` | yes | no | yes | yes |
| `for...in` | yes | yes | no | no |
| `Object.keys` / `values` / `entries` | yes | no | no | no |
| `Object.getOwnPropertyNames` | yes | no | yes | no |
| `Object.getOwnPropertySymbols` | yes | no | yes | symbols only |
| `Reflect.ownKeys` | yes | no | yes | yes |
| `JSON.stringify`, spread, `Object.assign` | yes | no | no | spread and assign: yes; JSON: no |
Gotcha: Copying Drops Inherited Properties
Spread syntax, Object.assign, and JSON.stringify read only own enumerable properties. Anything the object got through its prototype is lost:
const base = {
greet() {
return `Hi from ${this.name}`;
}
};
const user = Object.create(base);
user.name = 'Ada';
const copy = { ...user };
console.log(copy.name); // 'Ada'
console.log(copy.greet); // undefined
console.log(JSON.stringify(user)); // '{"name":"Ada"}'
// Preserve the prototype explicitly
const clone = Object.assign(Object.create(Object.getPrototypeOf(user)), user);
console.log(clone.greet()); // "Hi from Ada"structuredClone also returns a plain object and drops the prototype. If you need a clone that keeps its behavior, rebuild it through its constructor or with Object.create as shown above.
Gotcha: Validating Untrusted Keys
When a key comes from user input, in and plain property reads both see inherited names:
const handlers = {
save() {
return 'saved';
}
};
function dispatch(action) {
if (action in handlers) return handlers[action]();
return 'unknown action';
}
console.log(dispatch('save')); // 'saved'
console.log(dispatch('toString')); // '[object Object]' (unintended)
function safeDispatch(action) {
if (Object.hasOwn(handlers, action)) return handlers[action]();
return 'unknown action';
}
console.log(safeDispatch('toString')); // 'unknown action'Exercise
Given const p = { a: 1 }; Object.defineProperty(p, 'b', { value: 2, enumerable: false }); const c = Object.create(p); c.d = 4;, what do Object.keys(c), the keys from for (const k in c), 'b' in c, and Object.hasOwn(c, 'a') produce?
Show answer
Object.keys(c) is ['d'] because only own enumerable keys count. for...in yields d then a. It skips b because b is non-enumerable. 'b' in c is true because in follows the chain and ignores enumerability. Object.hasOwn(c, 'a') is false because a lives on p.
Exercise
A function copies a config object with { ...config }, and afterwards copy.validate() throws "copy.validate is not a function". The original config.validate() works. What is the likely cause, and how do you fix it?
Show answer
validate is inherited from config's prototype, and spread copies only own enumerable properties. Fix it by keeping the prototype: Object.assign(Object.create(Object.getPrototypeOf(config)), config). Alternatively, rebuild the object through its constructor or class.