Symbols in JavaScript
Unique keys that never collide, and the well-known ones with meaning.
const INTERNAL = Symbol("internal");
const tour = { slug: "patterns", [INTERNAL]: { cached: true } };
console.log(Object.keys(tour), JSON.stringify(tour));
console.log(tour[INTERNAL].cached, Object.getOwnPropertySymbols(tour).length);
console.log(Symbol("a") === Symbol("a"), Symbol.for("a") === Symbol.for("a"));
class Range {
constructor(to) { this.to = to; }
*[Symbol.iterator]() { for (let i = 1; i <= this.to; i += 1) yield i; }
get [Symbol.toStringTag]() { return "Range"; }
[Symbol.toPrimitive](hint) { return hint === "number" ? this.to : "range"; }
}
const range = new Range(3);
console.log([...range], `${range}`, +range, Object.prototype.toString
.call(range));
How it works
Symbol(\u0022x\u0022)is unique; the description is only a label.- A symbol key is skipped by JSON and by Object.keys.
- The well-known symbols hook into language behavior.
Keywords and builtins used here
JSONObjectSymbolclassconstconstructorforletreturnthisyield
The run, in numbers
- Lines
- 18
- Characters to type
- 676
- Tokens
- 215
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 117 seconds.
Step 2 of 4 in Objects under the hood, step 13 of 16 in Functions & patterns.