Creating Symbols with Symbol()
You'll learn how to create unique symbol values using JavaScript's Symbol() function and give them optional descriptions.
What is Symbol()?
Symbol() is a built-in function that creates a new, unique symbol value every time you call it. Think of it like a factory that produces one-of-a-kind identification badges—even if two badges look identical on the surface, they're fundamentally different underneath.
Basic Syntax
To create a symbol, simply call Symbol():
const mySymbol = Symbol();
console.log(typeof mySymbol); // "symbol"
Every call to Symbol() creates a completely unique value, even if they look the same:
const sym1 = Symbol();
const sym2 = Symbol();
console.log(sym1 === sym2); // false (always!)
Adding Optional Descriptions
You can pass a string description to Symbol() for debugging purposes. This description doesn't affect uniqueness—it's just a label:
const userId = Symbol("user identifier");
const userName = Symbol("user identifier");
console.log(userId === userName); // still false!
console.log(userId.description); // "user identifier"
The description makes your code more readable when debugging but doesn't change the symbol's behavior. Two symbols with identical descriptions remain distinct values.
Why This Matters
Unlike strings or numbers, symbols are guaranteed unique. You can't accidentally create the same symbol twice, making them perfect for creating collision-free property keys (which you'll learn about in upcoming lessons).
Key Takeaway: Use Symbol() to create guaranteed-unique values; add optional descriptions for debugging clarity, but remember that descriptions don't affect uniqueness—each Symbol() call always produces a distinct value.