Sub topic 3
What Can Be a Property Key: Strings and Symbols
This chapter assumes you can create objects with literals and read properties with dot and bracket notation, as covered in the previous chapters. It also assumes you know JavaScript's primitive types and can run code in Node.js or a browser console.
Every property has a key and a value. The value can be anything, but the key has to be one of exactly two types: a string or a symbol. If you use any other value as a key, JavaScript converts it to a string first. That one rule explains several surprising behaviors, such as numeric keys acting like strings and all plain objects sharing one key. Symbols are the other option. They give you keys that cannot clash with anyone else's and that most listing operations skip.
The Conversion Rule: Everything Else Becomes a String
When you write obj[expr], the engine evaluates expr and runs an internal step the specification calls ToPropertyKey. If the result is a symbol, the symbol is used as it is. Anything else is converted to a string.
Here are some primitives used as keys:
const obj = {};
obj[1] = "number one";
obj[true] = "yes";
obj[null] = "nothing";
obj[undefined] = "missing";
console.log(obj["1"]); // "number one"
console.log(obj["true"]); // "yes"
console.log(obj.null); // "nothing"
console.log(obj.undefined); // "missing"
console.log(Object.keys(obj)); // ["1", "true", "null", "undefined"]The object holds no number, boolean, or null key. It holds four string keys. obj[1] and obj["1"] refer to the same property.
Numbers become their canonical string form
A number is converted the way String(n) converts it. Number literals that are written differently but equal the same value end up as the same key. Strings that look like numbers are not normalized at all.
const scores = {};
scores[1.0] = "a"; // key "1"
scores[0.5] = "b"; // key "0.5"
scores[-0] = "c"; // key "0" (String(-0) is "0")
scores[1e21] = "d"; // key "1e+21"
scores["01"] = "e"; // key "01", a different key from "1"
console.log(Object.keys(scores)); // ["0", "1", "0.5", "1e+21", "01"]
console.log(scores[1] === scores["1"]); // true
console.log(scores["01"] === scores[1]); // falseNotice that "0" and "1" come first in the output. Keys that look like array indices are listed in ascending numeric order, ahead of the other string keys. A later chapter, "Listing Properties and Their Order", covers this in detail. The point here is that "01", "0.5", and "1e+21" are ordinary string keys, so they appear in insertion order.
Arrays work the same way. An array is an object, and its indices are string keys such as "0" and "1". When you write arr[2], the 2 is converted to "2". The engine optimizes arrays internally, but the language still treats their keys as strings.
const arr = ["x", "y", "z"];
console.log(arr["2"]); // "z"
console.log(Object.keys(arr)); // ["0", "1", "2"]Objects become "[object Object]"
This rule causes a classic bug. An object used as a key is converted to a primitive, usually by calling its toString method. For a plain object that returns "[object Object]", so every plain object maps to the same key:
const cache = {};
const a = { id: 1 };
const b = { id: 2 };
cache[a] = "first";
cache[b] = "second"; // overwrites: same key as a
console.log(Object.keys(cache)); // ["[object Object]"]
console.log(cache[a]); // "second"The data was not lost to a typo. Both writes went to the same string key. If you need to key data by object identity, use a Map, which accepts any value as a key and compares keys by identity:
const a = { id: 1 };
const b = { id: 2 };
const cache = new Map();
cache.set(a, "first");
cache.set(b, "second");
console.log(cache.get(a)); // "first"
console.log(cache.size); // 2An object with its own toString (or Symbol.toPrimitive) method controls the string it becomes. This makes the conversion visible, but it is rarely a good idea in real code:
const lookup = {};
const point = { x: 3, y: 4, toString() { return `${this.x},${this.y}`; } };
lookup[point] = "found";
console.log(Object.keys(lookup)); // ["3,4"]
console.log(lookup["3,4"]); // "found"Symbols: Unique Keys
A symbol is a primitive value whose only job is to be unique. You create one by calling Symbol(), optionally with a description. The description is a label for debugging. It does not affect identity.
const id = Symbol("id");
const otherId = Symbol("id");
console.log(typeof id); // "symbol"
console.log(id === otherId); // false: same description, different symbols
console.log(id.description); // "id"Symbol is not a constructor. new Symbol() throws a TypeError.
Using a symbol as a key
You read and write symbol-keyed properties with bracket notation and the symbol value. Dot notation always means a string key, so user.id looks up the string "id" and finds nothing:
const id = Symbol("id");
const user = { name: "Lin" };
user[id] = 42;
console.log(user[id]); // 42
console.log(user.id); // undefined
console.log(user["id"]); // undefinedTo put a symbol key inside an object literal, wrap it in brackets, as in { [id]: 42 }. That syntax is called a computed key. The next chapter covers it in full.
The main reason to use symbols is that they cannot collide. Suppose a library adds obj.id to objects you pass to it. It might overwrite your own id property. If the library uses a symbol it created, it cannot touch any key that existed before, and no other code can reach that property by accident.
Which operations see symbol keys
Most operations that list keys skip symbols. A few built-in functions look for them specifically.
const id = Symbol("id");
const user = { name: "Lin", [id]: 42 };
console.log(Object.keys(user)); // ["name"]
console.log(JSON.stringify(user)); // {"name":"Lin"}
for (const k in user) console.log(k); // name
console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]
console.log(Reflect.ownKeys(user)); // ["name", Symbol(id)]
const copy = { ...user };
console.log(copy[id]); // 42| Operation | Includes string keys | Includes symbol keys |
|---|---|---|
| `for...in` | yes (enumerable, including inherited) | no |
| `Object.keys`, `Object.values`, `Object.entries` | yes (own, enumerable) | no |
| `JSON.stringify` | yes (own, enumerable) | no |
| `Object.getOwnPropertyNames` | yes (own, all) | no |
| `Object.getOwnPropertySymbols` | no | yes (own, all) |
| `Reflect.ownKeys` | yes (own, all) | yes (own, all) |
| Spread `{ ...obj }` and `Object.assign` | yes (own, enumerable) | yes (own, enumerable) |
| `in` operator, `Object.hasOwn` | yes | yes |
Reflect.ownKeys returns integer-like keys first, then the other strings in insertion order, then symbols in insertion order.
Spread and Object.assign copy enumerable symbol keys, but JSON.stringify drops them. A round trip through JSON therefore loses symbol-keyed data without any error.
Converting a symbol to a string
Symbols refuse implicit conversion to strings. This catches the bug of building a string key from a symbol by mistake. An explicit conversion works:
const tag = Symbol("tag");
console.log(String(tag)); // "Symbol(tag)"
console.log(tag.toString()); // "Symbol(tag)"
console.log(tag.description); // "tag"
try {
console.log("key: " + tag);
} catch (e) {
console.log(e instanceof TypeError); // true
}Template literals throw the same way: ` ${tag} is a TypeError`.
The global symbol registry
Sometimes separate pieces of code, such as different modules or an iframe and its parent page, need the same symbol. Symbol.for(key) looks the key up in a registry shared by the whole runtime. It creates a symbol the first time and returns that same symbol on every later call.
const s1 = Symbol.for("app.session");
const s2 = Symbol.for("app.session");
console.log(s1 === s2); // true
console.log(Symbol.keyFor(s1)); // "app.session"
console.log(Symbol.keyFor(Symbol("local"))); // undefinedRegistered symbols share one global namespace, so they can collide just like string keys. Prefix registry keys with your package name.
Well-known symbols
The language defines some symbols of its own as static properties of Symbol. Built-in operations check for these "well-known symbols", which lets your objects hook into the operations without risking a clash with ordinary string keys.
| Symbol | Used by |
|---|---|
| `Symbol.iterator` | `for...of`, spread into arrays, destructuring |
| `Symbol.toPrimitive` | conversion to number or string, including key conversion |
| `Symbol.toStringTag` | `Object.prototype.toString` output |
| `Symbol.asyncIterator` | `for await...of` |
const range = {
from: 1,
to: 3,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next: () =>
current <= last
? { value: current++, done: false }
: { value: undefined, done: true }
};
},
[Symbol.toStringTag]: "Range"
};
console.log([...range]); // [1, 2, 3]
console.log(String(range)); // "[object Range]"
console.log(Object.keys(range)); // ["from", "to"]The object gains iteration and a custom tag, and Object.keys still reports only its data.
Choosing a Key Type
- Use string keys for ordinary data, anything you serialize, and anything callers should see when they list keys.
- Use local symbols (
Symbol("desc")) for metadata or hooks that must not collide with other keys and should stay out ofObject.keysand JSON. - Use registered symbols (
Symbol.for) only when separate code must agree on one key without sharing a variable. - Use a
Mapwhen the keys are objects or other non-string values whose identity matters.
Exercise
What does this code log, and why? const o = {}; o[2] = "a"; o["2"] = "b"; o[2.0] = "c"; o["2.0"] = "d"; console.log(Object.keys(o));
Show answer
It logs ["2", "2.0"]. The number 2, the string "2", and the number 2.0 all convert to the string key "2", so the second and third writes overwrite the first. The final value of o["2"] is "c". The string "2.0" is not normalized, so it is a separate key, and it is listed after "2" because only canonical index-like keys are sorted first.
Exercise
A function marks objects with obj[Symbol("seen")] = true and later checks obj[Symbol("seen")] to see whether it has already processed them. The check never returns true. Explain the bug and fix it.
Show answer
Each call to Symbol("seen") creates a new, unique symbol, so the check looks up a different key from the one that was written. Create the symbol once and reuse it, for example const SEEN = Symbol("seen"); at module level, then write obj[SEEN] = true and check obj[SEEN]. Use Symbol.for("mylib.seen") only if separate modules must share the key without importing the same variable.
Exercise
You store a symbol-keyed property on an object, then save the object with JSON.stringify and load it back with JSON.parse. The property is gone. A copy made with { ...obj } still has it. Why do the two behave differently?
Show answer
JSON.stringify only serializes own enumerable string keys and silently skips symbol keys. Spread syntax copies all own enumerable properties, including those with symbol keys. If the data must survive serialization, store it under a string key, or convert it to a string key explicitly before saving.