Sub topic 1
What a Symbol Is: A Unique Primitive
JavaScript has seven primitive types: string, number, bigint, boolean, undefined, null, and symbol. Most developers use the first six every day. Many have never called Symbol() on purpose. Symbols are still worth learning, because they are the reason for...of loops work, and they give you a way to attach data to objects without clashing with property names that other code uses.
This chapter covers the core idea: what a symbol value is, how you create one, and why two symbols are never equal unless they are the same value. Later chapters build on this to cover descriptions, property keys, the global registry, and the well-known symbols.
Prerequisites
This chapter assumes you already know:
- JavaScript primitive types and how
typeofreports them - Objects, property access with dot and bracket notation, and computed property names such as
{ [key]: value } - ES6 classes and methods
- Basic
for...ofloops and spread syntax ([...iterable])
You need a recent version of Node.js or a browser console to run the examples. Every snippet runs on its own.
The Core Idea: A Value That Equals Only Itself
A symbol is a primitive value whose only real property is its identity. A string like "id" is equal to every other string with the same characters. A symbol is equal only to itself. When you call Symbol(), you get a value that no earlier or later call will ever produce.
const a = Symbol('id');
const b = Symbol('id');
console.log(typeof a); // "symbol"
console.log(a === b); // false
console.log(a.description); // "id"
console.log(a.toString()); // "Symbol(id)"
// new Symbol('id'); // TypeError: Symbol is not a constructorEach line shows one fact:
typeof areturns"symbol", a type of its own. A symbol is not a string or an object.a === bisfalseeven though both calls passed'id'. The argument is a label for humans. It does not decide identity.a.descriptiongives back the label you passed in.a.toString()gives a readable form,"Symbol(id)", which helps when debugging.new Symbol()throws. You create symbols by callingSymbolas a plain function.
The next chapter covers descriptions and string conversion in detail. For now, the point is that the description has no effect on equality.
Identity Travels With the Value
Uniqueness belongs to the value, not to the variable that holds it. If you assign a symbol to another variable, pass it to a function, or store it in an array, it stays the same symbol. Every comparison operator agrees on this.
const token = Symbol('token');
const copy = token;
function same(x, y) {
return x === y;
}
console.log(copy === token); // true
console.log(same(token, copy)); // true
console.log(Object.is(token, copy)); // true
console.log(token == Symbol('token')); // false, loose equality does not help
const list = [token];
console.log(list.includes(token)); // true
console.log(list.includes(Symbol('token'))); // falseLoose equality (==) does not change anything here. With strings and numbers, == may convert types before it compares. A symbol only loosely equals itself.
This also means symbols work well as members of a Set or as Map keys. Each symbol counts as a separate entry:
const s1 = Symbol('red');
const s2 = Symbol('red');
const seen = new Set([s1, s2, s1]);
console.log(seen.size); // 2
const labels = new Map();
labels.set(s1, 'first');
labels.set(s2, 'second');
console.log(labels.get(s1)); // "first"
console.log(labels.get(s2)); // "second"Why Symbol Is Not a Constructor
Symbol is a function (typeof Symbol is "function"), but it refuses new. The language designers made this choice on purpose. new String('x') and new Number(1) create wrapper objects, and those objects cause bugs: new Boolean(false) is truthy, and new String('a') === 'a' is false. Throwing on new Symbol() keeps that mistake away from symbols.
A symbol still has a wrapper type. When you read a property such as .description from a symbol, JavaScript wraps it in a Symbol object for that one access, the same way it does for strings. You can create the wrapper yourself with Object(), though you rarely have a reason to:
const sym = Symbol('wrapped');
const boxed = Object(sym);
console.log(typeof sym); // "symbol"
console.log(typeof boxed); // "object"
console.log(boxed instanceof Symbol); // true
console.log(sym instanceof Symbol); // false, primitives are not instances
console.log(boxed.valueOf() === sym); // true
console.log(Object.getPrototypeOf(sym) === Symbol.prototype); // trueSymbols Are Immutable Primitives
Like other primitives, a symbol cannot be changed. You cannot add properties to it, and its description is fixed when it is created.
'use strict';
const sym = Symbol('fixed');
try {
sym.extra = 1;
} catch (e) {
console.log(e instanceof TypeError); // true in strict mode
}
console.log(sym.extra); // undefined
console.log(sym.description); // "fixed"Outside strict mode, the assignment fails silently and sym.extra stays undefined. In both modes the symbol is unchanged.
The Description Argument: What It Accepts
The argument to Symbol() is optional. JavaScript converts whatever you pass to a string, except undefined, which means "no description".
console.log(Symbol().description); // undefined
console.log(Symbol(undefined).description); // undefined
console.log(Symbol('').description); // ""
console.log(Symbol(42).description); // "42"
console.log(Symbol({}).description); // "[object Object]"The difference between no description and an empty description is small, but description does report it. Whatever the argument is, the identity rule stays the same: every call returns a new symbol.
Why Uniqueness Is Useful
Uniqueness solves the problem of name collisions. Suppose two libraries both want to tag the same object with a property called id. If both use the string 'id', one overwrites the other. If each library creates its own symbol, the two keys can never clash, because no other code can produce an equal value by accident.
const libAId = Symbol('id');
const libBId = Symbol('id');
const record = {};
record[libAId] = 'A-001';
record[libBId] = 'B-777';
console.log(record[libAId]); // "A-001"
console.log(record[libBId]); // "B-777"The "Using Symbols as Collision-Free Property Keys" chapter covers this pattern fully. What matters here is the reason it works: code can only reach a symbol by holding a reference to it. Typing the same description again does not recreate it.
Sometimes you want the opposite: two separate pieces of code that agree on one shared symbol. Symbol() cannot do that. The global registry (Symbol.for), covered in its own chapter, exists for that case.
Limits of the Symbol Primitive
Symbols act differently from other primitives in a few places. Knowing these early saves debugging time:
| Situation | Behavior with a symbol |
|---|---|
| `typeof sym` | `"symbol"` |
| `new Symbol()` | Throws `TypeError` |
| `sym instanceof Symbol` | `false` |
| `sym + ''` or `` `${sym}` `` | Throws `TypeError` (covered in the next chapter) |
| `Number(sym)` or `+sym` | Throws `TypeError` |
| `Boolean(sym)` or `if (sym)` | `true`, every symbol is truthy |
| `structuredClone(sym)` | Throws `DataCloneError` |
The structuredClone row also applies to postMessage and other APIs that copy data between workers or windows. A non-registered symbol's identity exists only inside one running program, so the runtime cannot copy it to another one in any meaningful way.
const sym = Symbol('flag');
console.log(Boolean(sym)); // true
try {
Number(sym);
} catch (e) {
console.log(e instanceof TypeError); // true
}
try {
structuredClone(sym);
} catch (e) {
console.log(e.name); // "DataCloneError"
}Common Mistakes
- Expecting equal descriptions to mean equal symbols.
Symbol('x') === Symbol('x')is alwaysfalse. If you need the same symbol in two places, create it once and export it, or use the global registry. - Recreating a symbol to look up a value.
obj[Symbol('id')]reads a brand-new key, so it always returnsundefined. Keep the original reference. - Calling
new Symbol(). This throws. CallSymbol()withoutnew. - Checking with
instanceof. Usetypeof value === 'symbol'. - Treating the description as data. The description is for debugging output. Don't build program logic on it, because nothing stops two symbols from sharing a description.
Exercise
What does this code print, and why? const k = Symbol('k'); const o = { [k]: 1 }; console.log(o[Symbol('k')], o[k]);
Show answer
It prints undefined 1. Symbol('k') inside the lookup creates a new symbol that differs from k, so the object has no property under that key. o[k] uses the original symbol and finds the value 1.
Exercise
Write a function isSymbol(value) that returns true for symbol primitives and false for everything else, including Object(Symbol()).
Show answer
function isSymbol(value) { return typeof value === 'symbol'; } The typeof check returns "symbol" only for the primitive. The wrapper made by Object(Symbol()) has typeof equal to "object", so it returns false. An instanceof Symbol check would get both cases wrong: it returns false for real symbols and true for wrappers.
Exercise
A Set is built with new Set([Symbol('a'), Symbol('a'), Symbol()]), and then const s = Symbol('b'); set.add(s); set.add(s); runs. What is set.size?
Show answer
4. Each of the three Symbol(...) calls in the array creates a separate value, giving 3 entries. Adding s adds one more. Adding s a second time does nothing, because it is the same value.