Sub topic 10
What Object.keys Skips: Symbols and Non-Enumerable Properties
This chapter assumes you already know how Object.keys and Object.entries loop over an object's own enumerable string-keyed properties, and that you can read object literals that use computed keys such as [id]: 7. In this chapter you look at the two kinds of own property those methods leave out, and at the methods that do return them.
Two Kinds of Hidden Property
An object can have own properties that Object.keys, Object.values, and Object.entries never report:
- Symbol-keyed properties. A symbol is a unique primitive value created with
Symbol(). When you use one as a property key, the property is keyed by that symbol instead of a string. The three methods only collect string keys, so they skip it. - Non-enumerable properties. Every property has an
enumerableflag. Properties you create with assignment or object literals have it set totrue. Properties created withObject.definePropertydefault tofalseunless you set the flag yourself. Built-in properties such as an array'slengthare also non-enumerable.
Library and framework authors often use both kinds on purpose. They let you attach metadata to an object without that metadata showing up in ordinary loops, JSON.stringify output, or key counts.
Seeing What Each Method Returns
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.entries(user)); // [['name', 'Ada']]
console.log(Object.getOwnPropertyNames(user)); // ['name', 'secret']
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]
console.log(Reflect.ownKeys(user)); // ['name', 'secret', Symbol(id)]
console.log(user.secret); // 'x'
console.log(user[id]); // 7
console.log(user.propertyIsEnumerable('secret')); // falseThe properties are hidden from enumeration only. Direct access with dot or bracket notation still works. Reflect.ownKeys returns string keys first, in the usual order, followed by symbol keys in the order they were added.
| Method | String keys, enumerable | String keys, non-enumerable | Symbol keys |
|---|---|---|---|
| `Object.keys` / `values` / `entries` | Yes | No | No |
| `Object.getOwnPropertyNames` | Yes | Yes | No |
| `Object.getOwnPropertySymbols` | No | No | Yes (enumerable or not) |
| `Reflect.ownKeys` | Yes | Yes | Yes |
None of these methods returns inherited properties. They all look only at the object's own properties.
Looping over Every Own Property
No built-in method returns entries for all keys, so you build the pairs yourself from Reflect.ownKeys:
const id = Symbol('id');
const user = { name: 'Ada', [id]: 7 };
Object.defineProperty(user, 'secret', { value: 'x', enumerable: false });
for (const key of Reflect.ownKeys(user)) {
console.log(String(key), user[key]);
}
// name Ada
// secret x
// Symbol(id) 7String(key) is needed because a template literal such as ` ${key} throws a TypeError when key is a symbol. Calling String()` on a symbol explicitly converts it to text safely.
Common Mistakes
- Counting with
Object.keys(obj).lengthand assuming that is every property. Symbols and non-enumerable keys are not counted. - Expecting
Object.definePropertyto behave like assignment. Besidesenumerable, thewritableandconfigurableflags also default tofalse. In the example above,user.secret = 'y'silently does nothing outside strict mode and throws aTypeErrorinside it. - Using
Object.getOwnPropertyNamesto find symbols. It only returns strings. You needObject.getOwnPropertySymbolsorReflect.ownKeys.
Exercise
Given const tag = Symbol('tag'); const o = { a: 1, [tag]: 2 }; Object.defineProperty(o, 'b', { value: 3 });, what do Object.keys(o), Object.getOwnPropertyNames(o), and Reflect.ownKeys(o) return, and what keys does { ...o } contain?
Show answer
Object.keys(o) returns ['a']. Object.getOwnPropertyNames(o) returns ['a', 'b'], because b is non-enumerable by default. Reflect.ownKeys(o) returns ['a', 'b', Symbol(tag)]. The spread copy contains a and [tag]: spread copies enumerable symbol keys but skips the non-enumerable b.
Exercise
What does Object.getOwnPropertyNames(['x']) return, and why does Object.keys(['x']) differ?
Show answer
It returns ['0', 'length']. An array's length is an own property, but it is non-enumerable, so Object.keys returns only ['0'].