Sub topic 3
What Can Be a Property Key: Strings and Symbols
This chapter assumes you can create object literals and read properties with dot and bracket notation. It also assumes you know JavaScript's primitive types.
Every property key in JavaScript is either a string or a symbol. No other key type exists. If you pass any other value as a key, JavaScript converts it to a string first. Most surprises with keys come from that conversion.
Everything else becomes a string
When you use bracket notation with a number, boolean, null, or undefined, the engine calls String() on the value and uses the result as the key.
const obj = {};
obj[1] = "number key";
obj[true] = "boolean key";
obj[null] = "null key";
console.log(Object.keys(obj)); // ["1", "true", "null"]
console.log(obj["1"]); // "number key"
console.log(obj[1] === obj["1"]); // trueobj[1] and obj["1"] refer to the same property. The same rule applies to arrays. Array indices are string keys such as "0" and "1", and engines optimize them internally.
Common error: objects as keys
An object used as a key becomes the string "[object Object]". Every plain object converts to that same string, so different objects end up overwriting one key.
const a = { id: 1 };
const b = { id: 2 };
const cache = {};
cache[a] = "first";
cache[b] = "second";
console.log(Object.keys(cache)); // ["[object Object]"]
console.log(cache[a]); // "second"Symbols: unique keys
A symbol is a primitive value that is guaranteed to be unique. Symbol() creates a new symbol. The optional string you pass is only a description for debugging, so two symbols with the same description are still different.
const id = Symbol("id");
const other = Symbol("id");
console.log(id === other); // false
console.log(id.description); // "id"
const user = { name: "Lin" };
user[id] = 42;
console.log(user[id]); // 42
console.log(user.id); // undefined
console.log(Object.keys(user)); // ["name"]
console.log(JSON.stringify(user)); // {"name":"Lin"}
console.log(Object.getOwnPropertySymbols(user)); // [ Symbol(id) ]
console.log(Reflect.ownKeys(user)); // [ "name", Symbol(id) ]Note user.id. Dot notation always uses the literal name as a string key, so it looks up "id" and not the symbol stored in the variable id. To use a symbol key you must use brackets.
Symbol keys are skipped by for...in, Object.keys, and JSON.stringify. Because of this, libraries can attach metadata to objects without conflicting with your string keys or appearing in serialized output. Symbol keys are still not private. Object.getOwnPropertySymbols and Reflect.ownKeys return them.
Shared symbols with `Symbol.for`
Symbol.for(key) looks up a global symbol registry. It returns the same symbol every time you pass the same string, even across modules.
const s1 = Symbol.for("app.userId");
const s2 = Symbol.for("app.userId");
console.log(s1 === s2); // true
console.log(Symbol.keyFor(s1)); // "app.userId"Well-known symbols
JavaScript defines built-in symbols that let objects hook into language features.
| Symbol | What it controls |
|---|---|
| `Symbol.iterator` | How `for...of` and spread iterate the object |
| `Symbol.toPrimitive` | How the object converts to a number or string |
| `Symbol.toStringTag` | The tag shown by `Object.prototype.toString` |
| `Symbol.asyncIterator` | How `for await...of` iterates the object |
const range = { from: 1, to: 3 };
range[Symbol.iterator] = function* () {
for (let i = this.from; i <= this.to; i++) yield i;
};
console.log([...range]); // [1, 2, 3]Exercise
Given const k = Symbol("x"); const o = { x: 1 }; o[k] = 2; o[2] = 3;, what do Object.keys(o), o.x, and o["2"] return?
Show answer
Object.keys(o) returns ["2", "x"]. The symbol key is skipped, and the number 2 was converted to the string "2", which is listed first as an integer-like key. o.x returns 1 because dot notation reads the string key "x" and not the symbol. o["2"] returns 3 because o[2] and o["2"] are the same key.
Exercise
Why does const m = {}; m[[1, 2]] = "a"; console.log(m["1,2"]); print "a"?
Show answer
The array is not a string or symbol, so it is converted with String(), which joins its elements into "1,2". The property is stored under that string key.