Sub topic 3
Enumerable Properties: What for...in Sees and Skips
This chapter assumes you know how to write a basic for...in loop, create objects with literals and classes, and read properties with dot and bracket access. It explains why some properties appear in a for...in loop and others never do, even though you can read them directly.
Every Property Has Attributes
A JavaScript property is more than a key and a value. Each property also carries attributes, which are hidden flags that control how it behaves. One of them is enumerable. When enumerable is true, the property shows up in key listings. When it is false, the property still exists and you can still read it, but most enumeration APIs act as if it is not there.
You can inspect the attributes with Object.getOwnPropertyDescriptor:
const user = { name: 'Ada' };
console.log(Object.getOwnPropertyDescriptor(user, 'name'));
// { value: 'Ada', writable: true, enumerable: true, configurable: true }Properties created by assignment or by an object literal are always enumerable. Non-enumerable properties usually come from one of three places: the language's built-in objects, class syntax, or an explicit call to Object.defineProperty.
Creating a Non-Enumerable Property
Object.defineProperty lets you set the attributes yourself. When it creates a new property, every attribute you leave out defaults to false, so the property is non-enumerable unless you say otherwise.
const account = { owner: 'Ada' };
Object.defineProperty(account, 'secret', {
value: 'hunter2',
enumerable: false
});
for (const key in account) {
console.log(key);
}
// owner
console.log(account.secret); // hunter2
console.log('secret' in account); // true
console.log(Object.keys(account)); // ['owner']
console.log(JSON.stringify(account)); // {"owner":"Ada"}
console.log(Object.getOwnPropertyNames(account)); // ['owner', 'secret']The secret property is real. Direct access and the in operator both find it. The for...in loop, Object.keys, and JSON.stringify skip it. Object.getOwnPropertyNames lists every own string key no matter what its enumerable flag says.
You can also hide an existing property, as long as it is still configurable:
const config = { debug: true, port: 8080 };
Object.defineProperty(config, 'debug', { enumerable: false });
console.log(Object.keys(config)); // ['port']
console.log(config.debug); // trueWhen the property already exists, defineProperty changes only the attributes you pass, so value and writable stay as they were. If the property has configurable: false, trying to change enumerable throws a TypeError.
Symbol Keys Are Always Skipped
for...in only produces string keys. Properties keyed by a Symbol never appear in it, even when they are enumerable.
const id = Symbol('id');
const item = { label: 'box', [id]: 42 };
for (const key in item) {
console.log(key);
}
// label
console.log(Object.keys(item)); // ['label']
console.log(Object.getOwnPropertySymbols(item)); // [Symbol(id)]
console.log(Reflect.ownKeys(item)); // ['label', Symbol(id)]
console.log({ ...item }); // { label: 'box', [Symbol(id)]: 42 }Spread syntax and Object.assign behave differently here. They copy own enumerable properties, and that includes symbol keys. If you write a deep-copy or merge helper with for...in, it will silently drop every symbol-keyed property.
Built-ins and Classes Hide Their Methods
Have you ever wondered why for...in over an empty object {} prints nothing, when the object inherits toString, hasOwnProperty, and others? Those methods live on Object.prototype and are non-enumerable. The same applies to length on arrays and to the methods on Array.prototype.
console.log(Object.getOwnPropertyDescriptor([], 'length').enumerable); // false
console.log(Object.getOwnPropertyDescriptor(Object.prototype, 'toString').enumerable); // falseClass syntax follows the same rule. Methods and accessors declared in a class body go on the prototype as non-enumerable properties. Fields assigned in the constructor, or declared as class fields, are ordinary enumerable own properties.
class Point {
label = 'point';
constructor(x, y) {
this.x = x;
this.y = y;
}
get length() {
return Math.hypot(this.x, this.y);
}
toString() {
return `(${this.x}, ${this.y})`;
}
}
const p = new Point(3, 4);
for (const key in p) {
console.log(key);
}
// label
// x
// yOlder code that adds methods to a constructor's prototype by assignment does not get this protection:
function Legacy() {
this.own = 1;
}
Legacy.prototype.greet = function () {
return 'hi';
};
for (const key in new Legacy()) {
console.log(key);
}
// own
// greetAssigning greet creates an enumerable property, so for...in lists it through the prototype chain. The next chapter shows how to filter out inherited keys like this one with Object.hasOwn.
How for...in Decides Which Keys to Yield
Here is the full rule. for...in walks the object and then each prototype in turn. For every string key, it yields the key only if the property is enumerable and no object earlier in the chain already used that name.
The "already seen" check also counts non-enumerable properties. As a result, a non-enumerable own property can hide an enumerable inherited one with the same name:
const proto = { hidden: 'from proto' };
const obj = Object.create(proto);
Object.defineProperty(obj, 'hidden', { value: 'own', enumerable: false });
let count = 0;
for (const key in obj) {
count++;
}
console.log(count); // 0
console.log(obj.hidden); // ownTwo more edge cases are worth knowing. Running for...in on null or undefined does not throw. The loop simply runs zero times. Running it on a string primitive yields the index keys '0', '1', and so on, because the string is wrapped in a String object whose index properties are enumerable.
Which API Sees What
| API | Own enumerable string keys | Own non-enumerable string keys | Symbol keys | Inherited enumerable keys |
|---|---|---|---|---|
| `for...in` | Yes | No | No | Yes |
| `Object.keys` / `values` / `entries` | Yes | No | No | No |
| `JSON.stringify` | Yes | No | No | No |
| Spread `{...obj}` / `Object.assign` | Yes | No | Enumerable only | No |
| `Object.getOwnPropertyNames` | Yes | Yes | No | No |
| `Object.getOwnPropertySymbols` | No | No | All | No |
| `Reflect.ownKeys` | Yes | Yes | All | No |
To test a single key, use obj.propertyIsEnumerable(key). It returns true only for an own property that is enumerable, so it returns false for anything inherited.
const o = { a: 1 };
Object.defineProperty(o, 'b', { value: 2 });
console.log(o.propertyIsEnumerable('a')); // true
console.log(o.propertyIsEnumerable('b')); // false
console.log(o.propertyIsEnumerable('toString')); // falseCommon Mistakes
- Expecting
for...inorObject.keysto list everything you can read. UseReflect.ownKeysfor a complete list of own keys. - Writing a cloning or merging helper with
for...in. It drops symbols, includes inherited keys, and loses non-enumerable properties along with their attributes. UsestructuredClonefor data, or copyObject.getOwnPropertyDescriptors(obj)when the attributes matter. - Forgetting that
definePropertydefaults tofalsefor every attribute. A property you define withoutenumerable: truewill be missing fromJSON.stringifyoutput.
Exercise
Given const s = Symbol('s'); const o = Object.create({ inherited: 1 }); o.a = 1; o[s] = 2; Object.defineProperty(o, 'b', { value: 3 });, what do for...in, Object.keys(o), and Reflect.ownKeys(o) each produce?
Show answer
for...in yields 'a' and then 'inherited'. Object.keys(o) returns ['a']. Reflect.ownKeys(o) returns ['a', 'b', Symbol(s)]. The b property is non-enumerable because defineProperty defaults enumerable to false. The symbol is excluded from both string-key APIs, and only for...in looks at the prototype.
Exercise
A class Temperature has a constructor that sets this.celsius and a getter get fahrenheit(). Why does JSON.stringify(new Temperature(20)) produce {"celsius":20}, and how could you include fahrenheit without making it an own property?
Show answer
The getter lives on Temperature.prototype as a non-enumerable accessor, and JSON.stringify serializes only own enumerable properties. Define a toJSON() method that returns { celsius: this.celsius, fahrenheit: this.fahrenheit }. JSON.stringify calls it and serializes the object it returns.
Exercise
Why does for (const k in {}) console.log(k) print nothing, even though ({}).toString exists?
Show answer
toString and the other methods on Object.prototype are non-enumerable. for...in does walk the prototype chain, but it skips every non-enumerable property it finds there.