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.

JavaScript6 min readConcept 48 of 62

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

// 1. Guaranteed Uniquenessconst sym1 = Symbol("id");
const sym2 = Symbol("id");

console.log(sym1 === sym2);
// 2. Hidden Object Keysconst user = {
name: "Alice",
[sym1]: 42
};

console.log(Object.keys(user));
// 3. Direct Accessconsole.log(user[sym1]);
CONSOLE
Click "Run Step 1" to begin execution...
iStep through the code. Notice how false proves uniqueness, and how the Symbol key completely disappears when checking Object.keys()!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the output of `Symbol('test') === Symbol('test')`?
  2. 2What happens when you run `Object.keys()` on an object that uses a Symbol as a key?
  3. 3How can you create a Symbol that is shared identically across different parts of your app without passing the variable?

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...in loops or Object.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.