Symbols & Well-Known Symbols
Discover JavaScript's most mysterious primitive. Learn how to use Symbols to create guaranteed-unique object keys and alter internal language behaviors.
Guaranteed Uniqueness
Symbol is a primitive data type in JavaScript, just like String or Number.
However, every single Symbol is completely, mathematically unique. Even if you give two Symbols the exact same description, they are not equal: Symbol('id') === Symbol('id') evaluates to false.
Hidden Object Keys
The primary use case for Symbols is creating 'hidden' properties on objects. Because a Symbol is guaranteed to be unique, you can use it as an object key without any fear that you might accidentally overwrite an existing property.
Furthermore, Symbol properties are completely ignored by standard loops like for...in and methods like Object.keys(). They are practically invisible to standard object inspection.
Creating and Using Symbols
You create a Symbol by calling the Symbol() function (never use the new keyword with Symbols). You can optionally pass a string description for debugging purposes.
javascript
const secretKey = Symbol('secret');
const user = { name: 'Alice', [secretKey]: 42 };
To read the value back, you must have access to the exact secretKey variable: console.log(user[secretKey]); // 42.
The Hidden Key
Review the code below. We create two identical-looking Symbols to prove they are unique, and then use one as a 'hidden' key on an object that escapes standard loops.
Symbol Inspector
const sym2 = Symbol("id");
console.log(sym1 === sym2);
name: "Alice",
[sym1]: 42
};
console.log(Object.keys(user));
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Every call to
Symbol()produces a mathematically unique primitive value. - Symbols are ideal for creating 'hidden' object keys that avoid naming collisions.
- Symbol keys do not show up in
for...inloops orObject.keys(). - Use
Symbol.for()to create or retrieve a shared Symbol from the global registry. - JavaScript uses 'Well-Known Symbols' (like
Symbol.iterator) to expose internal language hooks.
Done with this concept?
Mark it complete to track your progress. No login needed.