JavaScript · Question 77
What are Symbols in JavaScript, and how do well-known Symbols customize language behavior?
Direct answer
A Symbol is a unique primitive often used as a collision-resistant property key, while well-known Symbols such as Symbol.iterator and Symbol.toPrimitive provide protocol hooks that let objects participate in built-in language operations.
Two calls to Symbol("id") create distinct values even though their descriptions match. That makes Symbols useful for keys that should not collide with ordinary string property names. They are still properties, not truly private storage.
Well-known Symbols are more powerful because JavaScript itself looks for them. Defining obj[Symbol.iterator] can make an object iterable by for...of and spread syntax. Defining Symbol.toPrimitive customizes object-to-primitive conversion. Other well-known hooks participate in matching, species construction, and related protocols.
- Symbol-keyed properties are not returned by
Object.keys(). - Global-registry Symbols created by
Symbol.for()are intentionally shared by key and are different from fresh Symbols. - Use private class fields when you need language-enforced class privacy; a Symbol key can still be discovered through reflection such as
Reflect.ownKeys().