Symbol use cases
Learn real symbol uses like the enum pattern and extension-safe properties.
The enum pattern
JavaScript has no built-in enum type, but symbols offer a safe alternative. Instead of string constants, you can use symbols to represent fixed categories like colors, statuses, or roles.
Since each symbol is unique, two unrelated modules cannot accidentally share the same value. A typeof check acts as a brand verification: it proves that a value really belongs to your category.
Extension-safe properties
When you write a library and want to attach metadata to a user's object without risking name collisions, symbols are the answer. Because symbol keys do not appear in for...in or Object.keys, your metadata stays hidden.
The user cannot accidentally overwrite your keys, and you cannot accidentally overwrite theirs. This pattern is called extension-safe properties and is a favorite of library authors.
Exercise Apply the enum pattern
Create a Status object with symbols: Open: Symbol('open') and Closed: Symbol('closed'). Add a [Status.Open]: true property to the task object. Verify the brand with typeof Status.Open === 'symbol' and log the result.
Show example solution
const Status = {
Open: Symbol('open'),
Closed: Symbol('closed')
};
const task = {
[Status.Open]: true
};
console.log(typeof Status.Open === 'symbol');
Test yourself
-
In which case is a symbol the best fit?
- Representing fixed categories with unique values
- Converting a number to a string
- Reversing an array
- Deleting a property from an object
Show answer
Representing fixed categories with unique values — Correct. Symbols for fixed categories (color, status, role) build the enum pattern.
-
Complete the enum pattern
const Status = { Active: ____, Paused: Symbol('paused'), Done: Symbol('done') };Show answer
const Status = { Active: Symbol('active'), Paused: Symbol('paused'), Done: Symbol('done') }; -
Symbol use cases
- Enum pattern
- For fixed categories
- Extension-safe
- Avoids name collisions
- Brand check
- Verify with typeof
- Hidden from for...in
- Protects third-party data