Sub topic 10
What Object.keys Skips: Symbols and Non-Enumerable Properties
This chapter assumes you already know how Object.keys, Object.values, and Object.entries work, and that you're comfortable with for...of, destructuring, and basic array methods. Earlier chapters described these methods as returning an object's own enumerable string-keyed properties. This chapter covers the properties that rule leaves out, the reasons they are hidden, and the tools that can still reach them.
The Two Filters Object.keys Applies
Every property on an object has a key and a set of attributes. Object.keys filters the object's own properties twice:
- Key type. A property key is either a string or a symbol.
Object.keyskeeps only string keys. Number keys likeobj[1]are stored as strings, so they pass this filter. - Enumerability. Each property has an
enumerableattribute that is eithertrueorfalse.Object.keyskeeps only properties where it istrue.
A property fails if it does not pass both filters. Object.values and Object.entries use the same filters, so everything in this chapter applies to all three.
const id = Symbol('id');
const user = { name: 'Ada', [id]: 7 };
Object.defineProperty(user, 'secret', { value: 'x', enumerable: false });
console.log(Object.keys(user)); // ['name']
console.log(Object.getOwnPropertyNames(user)); // ['name', 'secret']
console.log(Reflect.ownKeys(user)); // ['name', 'secret', Symbol(id)]The user object has three own properties. Object.keys reports one of them. The other two still exist and can be read normally with user.secret and user[id]. They are left out of enumeration, but nothing makes them private.
Non-Enumerable Properties
How a property becomes non-enumerable
Properties you create with an object literal or plain assignment are always enumerable. A property becomes non-enumerable in two main ways:
- You create it with
Object.definePropertyorObject.definePropertiesand omitenumerableor set it tofalse. - The engine creates it that way. Examples include an array's
lengthand the methods that aclassbody places on the prototype.
You can check the attribute with Object.getOwnPropertyDescriptor or propertyIsEnumerable:
const user = { name: 'Ada' };
Object.defineProperty(user, 'secret', { value: 'x' });
console.log(Object.getOwnPropertyDescriptor(user, 'secret'));
// { value: 'x', writable: false, enumerable: false, configurable: false }
console.log(user.propertyIsEnumerable('name')); // true
console.log(user.propertyIsEnumerable('secret')); // false
console.log(user.secret); // 'x'
console.log('secret' in user); // trueBuilt-in non-enumerable properties
Arrays show the effect most clearly. length is an own property of every array, but it is non-enumerable, so Object.keys never returns it:
const letters = ['a', 'b'];
console.log(Object.keys(letters)); // ['0', '1']
console.log(Object.getOwnPropertyNames(letters)); // ['0', '1', 'length']This hiding is deliberate. length is metadata about the array, not one of its elements. If length showed up when you looped over the indexes, it would be a bug. Libraries use the same idea. A non-enumerable property can hold a cache or an internal flag without appearing in loops, JSON.stringify output, or spread copies.
Symbol Keys
Why symbols are excluded
A symbol is a unique primitive value created with Symbol('description'). Two symbols are never equal, even when their descriptions match, so a symbol key cannot collide with any other key. That makes symbols a good fit for attaching metadata or protocol hooks to an object without affecting code that treats the object as a string-keyed record.
The language uses symbols this way. Symbol.iterator, Symbol.toPrimitive, and Symbol.toStringTag are the hooks that for...of, type conversion, and Object.prototype.toString look for. If Object.keys returned symbols, every object with a custom iterator would add an unexpected entry to code that loops over its keys. So symbol keys are left out even when they are enumerable.
Retrieving symbol keys
Object.getOwnPropertySymbols returns only the symbol keys. Reflect.ownKeys returns all own keys:
const a = Symbol('a');
const b = Symbol('b');
const obj = { [b]: 'bee', z: 2, 5: 'five', [a]: 'ay' };
console.log(Object.keys(obj)); // ['5', 'z']
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(b), Symbol(a)]
console.log(Reflect.ownKeys(obj)); // ['5', 'z', Symbol(b), Symbol(a)]Reflect.ownKeys follows a fixed order: integer-like keys in ascending order, then other string keys in insertion order, then symbols in insertion order. Symbols always come last, even when they were added first, as Symbol(b) was here.
The Full Set of Key-Listing Tools
| Method | Own or inherited | String keys | Symbol keys | Non-enumerable |
|---|---|---|---|---|
| `Object.keys` / `values` / `entries` | Own only | Yes | No | No |
| `for...in` | Own and inherited | Yes | No | No |
| `Object.getOwnPropertyNames` | Own only | Yes | No | Yes |
| `Object.getOwnPropertySymbols` | Own only | No | Yes | Yes |
| `Reflect.ownKeys` | Own only | Yes | Yes | Yes |
None of these methods give you inherited non-enumerable properties or inherited symbols. To get those, walk the prototype chain yourself with Object.getPrototypeOf and call one of the own-key methods at each level.
Enumerable keys including symbols
No single built-in returns "own enumerable keys, strings and symbols". This combination matters because it is exactly the set that object spread and Object.assign copy. To build it, filter Reflect.ownKeys:
const tag = Symbol('tag');
const obj = { visible: 1, [tag]: 'meta' };
Object.defineProperty(obj, 'hidden', { value: 2, enumerable: false });
const enumerableKeys = Reflect.ownKeys(obj).filter((key) =>
Object.prototype.propertyIsEnumerable.call(obj, key)
);
console.log(enumerableKeys); // ['visible', Symbol(tag)]The example calls propertyIsEnumerable through Object.prototype instead of as obj.propertyIsEnumerable. The borrowed form still works when the object has no prototype (Object.create(null)) or has its own property named propertyIsEnumerable.
How Other Operations Treat Hidden Properties
Different built-in operations apply different filters. Copying or serializing an object can therefore drop properties you expected to keep, or keep ones you expected to drop.
const tag = Symbol('tag');
const src = { visible: 1, [tag]: 'meta' };
Object.defineProperty(src, 'hidden', { value: 2, enumerable: false });
const spread = { ...src };
const assigned = Object.assign({}, src);
console.log(Reflect.ownKeys(spread)); // ['visible', Symbol(tag)]
console.log(Reflect.ownKeys(assigned)); // ['visible', Symbol(tag)]
console.log(JSON.stringify(src)); // {"visible":1}
console.log(Object.entries(src)); // [ [ 'visible', 1 ] ]| Operation | Copies enumerable symbols | Copies non-enumerable |
|---|---|---|
| `{ ...obj }` | Yes | No |
| `Object.assign` | Yes | No |
| `Object.entries` + `Object.fromEntries` | No | No |
| `JSON.stringify` | No | No |
The third row is a real trap. The entries-map-fromEntries pattern from the previous chapter silently drops symbol-keyed properties, while spread keeps them. If an object carries symbol metadata, rebuilding it with Object.fromEntries loses that metadata.
Copying everything, attributes included
To copy every own property with its attributes intact, copy the property descriptors:
const tag = Symbol('tag');
const src = { visible: 1, [tag]: 'meta' };
Object.defineProperty(src, 'hidden', { value: 2, enumerable: false });
const clone = Object.defineProperties(
{},
Object.getOwnPropertyDescriptors(src)
);
console.log(Reflect.ownKeys(clone)); // ['visible', 'hidden', Symbol(tag)]
console.log(Object.keys(clone)); // ['visible']
console.log(clone.hidden); // 2Object.getOwnPropertyDescriptors reads every own key, the same set Reflect.ownKeys returns. The clone keeps hidden non-enumerable, so it still stays out of Object.keys. This method also copies getters and setters as working accessors. Spread and Object.assign call a getter once and store the result as a plain value.
Gotchas and Failure Modes
Symbols in template literals throw
A loop over Reflect.ownKeys that worked during testing can crash the first time it meets a symbol:
const id = Symbol('id');
const record = { name: 'Ada', [id]: 7 };
for (const key of Reflect.ownKeys(record)) {
// `${key}` would throw: TypeError: Cannot convert a Symbol value to a string
console.log(`${String(key)} = ${String(record[key])}`);
}
// name = Ada
// Symbol(id) = 7Implicit conversion of a symbol to a string, as in template literals or '' + key, throws a TypeError. Explicit String(key) and key.toString() work. You can also check typeof key === 'symbol' and handle symbols separately.
Reflect.ownKeys does not coerce primitives
Object.keys('hi') converts the string to an object and returns ['0', '1']. Reflect.ownKeys requires a real object and throws when given a primitive:
console.log(Object.getOwnPropertyNames('hi')); // ['0', '1', 'length']
try {
Reflect.ownKeys('hi');
} catch (err) {
console.log(err instanceof TypeError); // true
}If a value might be a primitive, check typeof value === 'object' && value !== null before you call Reflect.ownKeys.
Hiding is not security
A non-enumerable property or a symbol key keeps data out of ordinary loops and JSON output. It does not stop anyone from reading the data. Any code holding the object can call Reflect.ownKeys and read every value. For real privacy, use class private fields (#field), a closure, or a WeakMap. None of those can be discovered by any key-listing method.
When to Reach Past Object.keys
In most application code, Object.keys and Object.entries are the right choice. Their filtering matches what "the data in this object" usually means. Use the wider tools for specific jobs:
- Debugging and inspection:
Reflect.ownKeysshows everything an object actually holds. - Faithful cloning or library utilities:
Object.getOwnPropertyDescriptorskeeps attributes, accessors, and symbols. - Protocol checks:
Object.getOwnPropertySymbolsfinds symbol hooks without pulling in string data. - Merging that must respect symbols: use spread or
Object.assigninstead ofObject.fromEntries.
Exercise
Given const k = Symbol('k'); const o = { b: 1, [k]: 2, 3: 'x' }; Object.defineProperty(o, 'a', { value: 4, enumerable: false });, what do Object.keys(o), Object.getOwnPropertyNames(o), and Reflect.ownKeys(o) return?
Show answer
Object.keys(o) returns ['3', 'b']. Object.getOwnPropertyNames(o) returns ['3', 'b', 'a'], which adds the non-enumerable a in insertion order after b. Reflect.ownKeys(o) returns ['3', 'b', 'a', Symbol(k)], with the integer-like key first, then string keys in insertion order, then the symbol last.
Exercise
A teammate doubles the numeric values of an object with Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, value * 2])). The object also has a symbol-keyed property [meta]: 'v1' that must survive. Why does it disappear, and how can you fix it?
Show answer
Object.entries returns only string keys, so the symbol property never reaches fromEntries. One fix is to copy the symbols back afterward: const out = Object.fromEntries(...); for (const s of Object.getOwnPropertySymbols(obj)) out[s] = obj[s];. Another fix is to build the result from the start with Reflect.ownKeys(obj) and a reduce that handles each key, doubling only the string-keyed numeric values.
Exercise
Why does for (const key of Reflect.ownKeys(obj)) console.log(Key: ${key}) crash on some objects but not others, and what is the smallest fix?
Show answer
It crashes only on objects that have symbol keys, because a template literal implicitly converts a symbol to a string, and that throws a TypeError. The smallest fix is explicit conversion: ` Key: ${String(key)} `.