Sub topic 4
Where Symbol Keys Show Up and Where They Stay Hidden
This chapter assumes you know how to create symbols with Symbol() and how to use them as computed property keys ({ [key]: value }). It also assumes you are comfortable with Object.keys, for...in, spread syntax, and JSON.stringify.
Symbol-keyed properties are ordinary properties. They hold values, they can be read and written, and they have property descriptors like any other property. They differ from string keys in one way: most of the built-in tools for listing an object's keys were designed before symbols existed, and they ignore symbols on purpose. That choice lets symbols be added to the language without breaking old code that loops over keys. It also leaves you with a split set of APIs: some see symbol keys, some skip them, and a few quietly copy them along.
This chapter maps that split so you can predict what happens to symbol-keyed data when your object is listed, copied, logged, or serialized.
The Two Families of Key-Listing APIs
The language keeps two lists of keys on every object: string keys and symbol keys. Each reflection API reads one list, the other, or both.
const id = Symbol('id');
const user = { name: 'Ada', [id]: 42 };
console.log(user[id]); // 42
console.log(Object.keys(user)); // ['name']
console.log(JSON.stringify(user)); // {"name":"Ada"}
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]
console.log(Reflect.ownKeys(user)); // ['name', Symbol(id)]Direct access with user[id] always works, because you hold the symbol. Listing is where behavior diverges. Object.keys and JSON.stringify only look at string keys. Object.getOwnPropertySymbols looks only at symbol keys. Reflect.ownKeys returns both.
The Full Reference Table
The table lists the common operations and how each treats own symbol-keyed properties.
| Operation | Sees symbol keys? | Notes |
|---|---|---|
| `Object.keys`, `Object.values`, `Object.entries` | No | Own enumerable string keys only |
| `for...in` | No | Also walks inherited enumerable string keys |
| `Object.getOwnPropertyNames` | No | Includes non-enumerable string keys, but no symbols |
| `JSON.stringify` | No | Symbol keys are dropped; the replacer never sees them |
| `structuredClone` | No | Symbol-keyed properties are not cloned |
| `Object.getOwnPropertySymbols` | Yes | Own symbol keys, enumerable or not |
| `Reflect.ownKeys` | Yes | Every own key, strings and symbols, enumerable or not |
| `Object.getOwnPropertyDescriptors` | Yes | Descriptors for every own key |
| `Object.assign` | Yes | Copies own enumerable string and symbol keys |
| Object spread `{ ...obj }` | Yes | Same rule as `Object.assign` |
| `key in obj`, `Object.hasOwn(obj, key)` | Yes | Work with any key you already hold |
| `Object.freeze`, `Object.seal` | Yes | Apply to symbol-keyed properties too |
| Node.js `console.log` | Yes | Prints keys as `[Symbol(id)]: 42` |
Two rows tend to surprise people. Spread and Object.assign do copy symbol keys, so symbols are not "invisible" to copying. And structuredClone does not copy them, so a deep clone loses data that a shallow spread keeps.
Copying: Spread Keeps Symbols, Serialization Drops Them
The difference matters whenever you clone an object. This example tags an object with metadata and then copies it three ways.
const meta = Symbol('meta');
const original = { title: 'Report', [meta]: { createdBy: 'system' } };
const spread = { ...original };
const assigned = Object.assign({}, original);
const viaJson = JSON.parse(JSON.stringify(original));
const cloned = structuredClone(original);
console.log(spread[meta]); // { createdBy: 'system' }
console.log(assigned[meta]); // { createdBy: 'system' }
console.log(viaJson[meta]); // undefined
console.log(cloned[meta]); // undefinedThe spread copy and the Object.assign copy share the same metadata object as the original, because both are shallow copies. The JSON round trip and structuredClone produce fresh objects with no symbol key at all.
You can treat this as a feature. Symbol keys work well for runtime-only bookkeeping, such as a cache, a "dirty" flag, or a back-reference, that should never reach a server or a saved file.
JSON.stringify and Symbol Values
JSON.stringify handles symbols in three places, and each has its own rule:
- A symbol key is skipped entirely.
- A symbol value inside an object makes that property disappear, just as
undefinedand functions do. - A symbol value inside an array becomes
null, so array positions stay intact.
const s = Symbol('x');
console.log(JSON.stringify({ [s]: 1, a: 2 })); // {"a":2}
console.log(JSON.stringify({ a: s, b: 2 })); // {"b":2}
console.log(JSON.stringify([s, 2])); // [null,2]
console.log(JSON.stringify(s)); // undefinedThe last line returns the value undefined, not the string "undefined". Code that does JSON.stringify(x).length will throw if x is a symbol.
A replacer function cannot rescue symbol keys, because JSON.stringify never passes them to it. If you need symbol-keyed data in the output, use a toJSON method and copy it to a string key yourself:
const version = Symbol('version');
const doc = {
body: 'Hello',
[version]: 3,
toJSON() {
return { body: this.body, version: this[version] };
}
};
console.log(JSON.stringify(doc)); // {"body":"Hello","version":3}Enumerability Still Applies
Symbol-keyed properties have an enumerable flag like any other property. This flag decides what spread and Object.assign copy. It does not affect Object.getOwnPropertySymbols or Reflect.ownKeys, which list non-enumerable keys too.
const visible = Symbol('visible');
const quiet = Symbol('quiet');
const obj = { [visible]: 1 };
Object.defineProperty(obj, quiet, { value: 2, enumerable: false });
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(visible), Symbol(quiet)]
console.log(Object.getOwnPropertySymbols({ ...obj })); // [Symbol(visible)]
console.log(obj.propertyIsEnumerable(quiet)); // falseSo a symbol key can be made to survive a reflection scan while being skipped by spread, or the other way around. When you design metadata keys, decide whether copies of the object should carry them, and set enumerable to match.
Inherited Symbol Keys
Object.getOwnPropertySymbols and Reflect.ownKeys only return own keys. Symbol keys on the prototype are still reachable with in and normal property access, but you have to walk the prototype chain to list them:
const tag = Symbol('tag');
class Base {}
Base.prototype[tag] = 'base';
const item = new Base();
console.log(tag in item); // true
console.log(item[tag]); // "base"
console.log(Object.hasOwn(item, tag)); // false
console.log(Object.getOwnPropertySymbols(item)); // []
function allSymbolKeys(o) {
const keys = [];
for (let p = o; p !== null; p = Object.getPrototypeOf(p)) {
keys.push(...Object.getOwnPropertySymbols(p));
}
return keys;
}
console.log(allSymbolKeys(item).includes(tag)); // trueRunning allSymbolKeys on any plain object also returns the well-known symbols defined on Object.prototype and the class prototypes, such as Symbol.toStringTag on some built-ins. Filter the results if you only want your own keys.
Key Order in Reflect.ownKeys
Reflect.ownKeys returns keys in a fixed order defined by the specification:
- Integer-like string keys (
"0","1","42") in ascending numeric order. - Other string keys in insertion order.
- Symbol keys in insertion order.
const first = Symbol('first');
const second = Symbol('second');
const obj = { b: 1, [second]: 2, 2: 3, a: 4, [first]: 5, 1: 6 };
console.log(Reflect.ownKeys(obj));
// ['1', '2', 'b', 'a', Symbol(second), Symbol(first)]Symbols always come after every string key, even if they were added first. If you rebuild an object from Reflect.ownKeys, its string keys and symbol keys will each keep their order, but the two groups will not be mixed together the way they were in the source code.
Common Errors
- Assuming
Object.keys(a).length === Object.keys(b).lengthmeans equal objects. Two objects can differ only in symbol keys. UseReflect.ownKeysfor a full comparison. - Using a JSON round trip as a deep clone. It drops symbol keys and symbol values silently.
structuredClonedrops symbol keys too and throws aDataCloneErroron symbol values. - Expecting spread to strip metadata. Spread copies enumerable symbol keys. Define the property with
enumerable: falseif copies should not carry it. - Treating "skipped by
Object.keys" as "hidden". Any code holding the object can callObject.getOwnPropertySymbolsand read the value. A later chapter compares symbols with private fields and WeakMaps for real data hiding.
A Complete Key-Inspection Helper
This helper sorts an object's own keys into the groups used in this chapter. It is handy for debugging objects that carry symbol metadata.
function describeKeys(obj) {
const result = { enumerableStrings: [], hiddenStrings: [], enumerableSymbols: [], hiddenSymbols: [] };
for (const key of Reflect.ownKeys(obj)) {
const isSymbol = typeof key === 'symbol';
const enumerable = Object.getOwnPropertyDescriptor(obj, key).enumerable;
const bucket = (enumerable ? 'enumerable' : 'hidden') + (isSymbol ? 'Symbols' : 'Strings');
result[bucket].push(isSymbol ? key.toString() : key);
}
return result;
}
const s = Symbol('s');
const sample = { a: 1, [s]: 2 };
Object.defineProperty(sample, 'secret', { value: 3, enumerable: false });
console.log(describeKeys(sample));
// {
// enumerableStrings: ['a'],
// hiddenStrings: ['secret'],
// enumerableSymbols: ['Symbol(s)'],
// hiddenSymbols: []
// }Exercise
Given const k = Symbol('k'); const src = { x: 1, [k]: 2 };, what do Object.keys({ ...src }), Object.getOwnPropertySymbols({ ...src }).length, and structuredClone(src)[k] return?
Show answer
Object.keys({ ...src }) returns ['x'], because Object.keys never lists symbols. Object.getOwnPropertySymbols({ ...src }).length is 1, because spread copies own enumerable symbol keys. structuredClone(src)[k] is undefined, because the structured clone algorithm copies only string keys.
Exercise
What does JSON.stringify({ list: [Symbol('a'), 1], flag: Symbol('b'), n: 0 }) produce, and why?
Show answer
It produces {"list":[null,1],"n":0}. A symbol inside an array becomes null so the array keeps its positions. A symbol as an object property value causes that property (flag) to be left out.
Exercise
You want to attach a cache to objects using a symbol key so that the cache is never copied by { ...obj } but debugging tools can still find it through reflection. How do you define it?
Show answer
Use Object.defineProperty(obj, cacheKey, { value: new Map(), enumerable: false, writable: true }). Spread and Object.assign skip non-enumerable properties, while Object.getOwnPropertySymbols and Reflect.ownKeys still list the key.