Sub topic 1
What Gets Iterated: Own Enumerable Properties
Before you loop over an object, you need to know which properties the loop will visit. Object.keys, Object.values, and Object.entries don't return everything an object can reach. They return a filtered set: the object's own, enumerable, string-keyed properties. This chapter explains each of those three words, shows how to test for them, and explains why the filter is what you want most of the time.
The later chapters cover the methods themselves. This chapter covers the rules those methods follow.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript variables, functions, and arrow functions
- Object literals and property access with dot and bracket notation (
obj.name,obj['name']) - Arrays and the
for...ofloop - Basic array methods such as
forEach,map, andfilter
You don't need any previous knowledge of prototypes or property descriptors. Both are introduced here.
A Property Is More Than a Name and a Value
Every property on a JavaScript object carries hidden metadata called a property descriptor. A descriptor is a small record of flags that says how the property behaves. You can read it with Object.getOwnPropertyDescriptor.
const user = { name: 'Ada' };
console.log(Object.getOwnPropertyDescriptor(user, 'name'));
// { value: 'Ada', writable: true, enumerable: true, configurable: true }The descriptor has four fields:
| Field | Meaning |
|---|---|
| `value` | The data stored in the property |
| `writable` | Whether assignment can change the value |
| `enumerable` | Whether the property shows up in key listings and `for...in` |
| `configurable` | Whether the property can be deleted or have its descriptor changed |
Properties you create with object literals or plain assignment (user.age = 36) always get enumerable: true. That's why everyday objects behave as you expect when you loop over them. The flag only becomes false when someone sets it on purpose, or when the language creates the property for you, as it does for many built-in properties.
Test One: Is the Property Own?
An own property lives directly on the object. An inherited property lives on another object in the prototype chain. The prototype chain is the linked series of objects JavaScript searches when you read a property the object doesn't have itself.
Object.create(proto) makes a new object whose prototype is proto. That gives you an easy way to see the difference:
const defaults = { theme: 'light', fontSize: 14 };
const prefs = Object.create(defaults);
prefs.theme = 'dark';
console.log(prefs.theme); // 'dark' (own property)
console.log(prefs.fontSize); // 14 (inherited from defaults)
console.log(Object.hasOwn(prefs, 'theme')); // true
console.log(Object.hasOwn(prefs, 'fontSize')); // false
console.log('fontSize' in prefs); // true
console.log(Object.keys(prefs)); // ['theme']Reading prefs.fontSize works because the lookup walks up to defaults. Object.keys doesn't walk anywhere, so it reports only theme.
Two checks are useful here:
Object.hasOwn(obj, key)returnstrueonly for own properties. It was added in ES2022. Older code usesObject.prototype.hasOwnProperty.call(obj, key)for the same check.key in objreturnstruefor own and inherited properties.
Test Two: Is the Property Enumerable?
An enumerable property has enumerable: true in its descriptor. Non-enumerable properties still exist, and you can read and write them normally, but key listings skip them.
You can create one with Object.defineProperty. Flags you leave out of the descriptor default to false:
const account = { owner: 'Ada' };
Object.defineProperty(account, 'internalId', {
value: 'acc-001',
enumerable: false,
});
console.log(account.internalId); // 'acc-001'
console.log(Object.hasOwn(account, 'internalId')); // true
console.log(account.propertyIsEnumerable('internalId')); // false
console.log(account.propertyIsEnumerable('owner')); // true
console.log(Object.keys(account)); // ['owner']internalId is an own property, but it fails the enumerable test, so Object.keys leaves it out.
The language uses non-enumerable properties all over its built-ins. The point is to keep machinery out of your data:
const list = ['a', 'b'];
console.log(Object.getOwnPropertyDescriptor(list, 'length'));
// { value: 2, writable: true, enumerable: false, configurable: false }
console.log(Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable);
// false
console.log(Object.keys(list)); // ['0', '1']An array's length is an own property, but nobody wants it in a list of the array's elements, so it is non-enumerable.
Class Methods Fail Both Tests
Classes are where this most often surprises people. Methods declared in a class body are placed on the class's prototype, not on each instance, and they are made non-enumerable:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distance() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
console.log(p.distance()); // 5
console.log(Object.hasOwn(p, 'distance')); // false
console.log(Object.getOwnPropertyDescriptor(Point.prototype, 'distance').enumerable); // false
console.log(Object.keys(p)); // ['x', 'y']So a class instance's keys are just the fields assigned to it. Usually that's the instance's data, which is what you want.
Test Three: Is the Key a String?
Property keys come in two types: strings and symbols. A symbol is a unique value created with Symbol(). It is often used as a property key that can't collide with any other key. Numbers used as keys are converted to strings, so obj[1] and obj['1'] refer to the same property.
Object.keys, Object.values, and Object.entries skip symbol keys, even when the symbol-keyed property is own and enumerable:
const version = Symbol('version');
const config = { mode: 'strict', 42: 'answer', [version]: 3 };
console.log(config[version]); // 3
console.log(config.propertyIsEnumerable(version)); // true
console.log(Object.keys(config)); // ['42', 'mode']Notice that the key 42 comes back as the string '42', and it comes before mode. A later chapter covers why integer-like keys come first. A later chapter also covers how to retrieve symbol keys when you need them.
Putting the Three Tests Together
A property appears in Object.keys, Object.values, and Object.entries only if it passes all three tests.
The following helper runs the same three tests on a single key. It's useful when debugging why a property does or doesn't show up:
function explainKey(obj, key) {
const own = Object.hasOwn(obj, key);
const enumerable = own && Object.prototype.propertyIsEnumerable.call(obj, key);
const stringKey = typeof key === 'string';
return { own, enumerable, stringKey, included: own && enumerable && stringKey };
}
const tag = Symbol('tag');
const base = { inherited: 1 };
const obj = Object.create(base);
obj.visible = 2;
obj[tag] = 3;
Object.defineProperty(obj, 'hidden', { value: 4 });
for (const key of ['visible', 'inherited', 'hidden', tag]) {
console.log(String(key), explainKey(obj, key));
}
// visible { own: true, enumerable: true, stringKey: true, included: true }
// inherited { own: false, enumerable: false, stringKey: true, included: false }
// hidden { own: true, enumerable: false, stringKey: true, included: false }
// Symbol(tag) { own: true, enumerable: true, stringKey: false, included: false }
console.log(Object.keys(obj)); // ['visible']The helper calls propertyIsEnumerable through Object.prototype instead of obj.propertyIsEnumerable. That way it still works on objects created with Object.create(null), which have no prototype and so no inherited methods.
Why This Filter Is the Right Default
Own enumerable string keys are a close match for "the data stored in this object". The filter excludes:
- Inherited methods and defaults, which belong to the prototype, not the object.
- Built-in machinery like
length, which the language hides on purpose. - Symbol-keyed metadata, which libraries often attach so it stays out of normal code paths.
Other parts of the language use similar rules, which keeps behavior consistent. The table compares common operations:
| Operation | Own only | Enumerable only | Includes symbol keys |
|---|---|---|---|
| `Object.keys` / `values` / `entries` | Yes | Yes | No |
| `JSON.stringify` | Yes | Yes | No |
| Object spread `{ ...obj }` | Yes | Yes | Yes |
| `Object.assign` | Yes | Yes | Yes |
| `for...in` | No, includes inherited | Yes | No |
| `Object.getOwnPropertyNames` | Yes | No | No |
| `Reflect.ownKeys` | Yes | No | Yes |
JSON.stringify uses the same rules as Object.keys, so the keys you loop over are the keys that get serialized. Spread and Object.assign differ in one respect: they copy enumerable symbol-keyed properties too.
Common Errors
- Expecting inherited defaults to appear. With
Object.create(defaults)patterns,Object.keysshows only the overrides. If you need the merged view, build it explicitly with{ ...defaults, ...overrides }instead of relying on the prototype chain. - Expecting class methods in the keys. Methods live on the prototype and are non-enumerable. Getters defined with
getin a class body are also on the prototype, so they're skipped too. - Assuming
inandObject.keysagree.'toString' in {}istrue, butObject.keys({})is[]. UseObject.hasOwnwhen you mean "does this object itself have the key". - Losing symbol-keyed data. If an object uses symbol keys for real data, a loop over
Object.entriessilently drops it. - Forgetting that a getter in an object literal is an ordinary own enumerable property.
{ get full() { return 'x'; } }hasfullin its keys, andObject.valuescalls the getter to produce the value.
Exercise
Given const proto = { a: 1 }; const o = Object.create(proto); o.b = 2; Object.defineProperty(o, 'c', { value: 3 }); o[Symbol('d')] = 4;, what does Object.keys(o) return, and which test excludes each of the other properties?
Show answer
It returns ['b']. a is inherited, so it fails the own test. c was created with defineProperty without enumerable: true, so it is non-enumerable. The Symbol('d') property is own and enumerable but has a symbol key, so it fails the string-key test.
Exercise
A class User sets this.name and this.email in its constructor and declares a method greet(). Why does Object.keys(new User('Ada', '[email protected]')) return ['name', 'email'] and not include greet?
Show answer
greet is defined on User.prototype, not on the instance, so it is inherited and fails the own test. Class methods are also created as non-enumerable, so it would be skipped even if checked directly on the prototype.
Exercise
'hasOwnProperty' in {} is true. Is 'hasOwnProperty' in Object.keys({})? Give two separate reasons.
Show answer
No, Object.keys({}) is []. First, hasOwnProperty is inherited from Object.prototype, so it is not an own property. Second, the built-in methods on Object.prototype are non-enumerable.