What is a Symbol?
Learn to create a unique, immutable primitive value with Symbol.
What is a Symbol?
In JavaScript, Symbol is the seventh primitive type; like numbers, strings and booleans, it is immutable. Calling Symbol() returns a unique value unlike any other.
Here is the interesting part: calling Symbol('id') twice produces different symbols each time. The text in parentheses is just a description label for debugging; it does not affect identity. typeof Symbol() returns 'symbol'.
The description label
The text in parentheses is a description label. Symbol('user').description returns 'user'; if no description is given, it returns undefined.
The label is only for debugging: console.log shows the symbol as Symbol(user). Even when two symbols share the same description, their identities remain different. The description plays no role in equality comparison.
Exercise Create two symbols and compare them
Create two symbols in the variables first and second. Give both the description 'id'. Log that first is 'symbol' using typeof. Then log the result of first !== second.
Show example solution
const first = Symbol('id');
const second = Symbol('id');
console.log(typeof first === 'symbol');
console.log(first !== second);
Test yourself
-
Which statement about Symbol is true?
- Symbol('x') === Symbol('x') returns false
- Symbol('x') === Symbol('x') returns true
- Symbol() returns an object
- typeof Symbol() returns 'object'
Show answer
Symbol('x') === Symbol('x') returns false — Correct. Each Symbol() call produces a unique value; even with the same description, two symbols are never equal.
-
Show that two symbols are different
const different = Symbol('x') ____ Symbol('x');Show answer
const different = Symbol('x') !== Symbol('x'); -
Match the Symbol concepts
- Symbol()
- Creates a unique value
- description
- Debugging label
- typeof Symbol()
- Returns 'symbol'
- Symbol('x') === Symbol('x')
- Returns false