What is Symbol in JS?
In JavaScript, a Symbol
is a unique and immutable primitive data type introduced in ES6 (ECMAScript 2015). It is often used as a key for object properties to ensure that the property is unique and does not conflict with other property keys, even if they have the same name.
const sym1 = Symbol("description");
const sym2 = Symbol("description");
console.log(sym1 === sym2); // false (Each Symbol is unique)
Key Features of Symbol
- Uniqueness: Each
Symbol
value is unique, even if created with the same description. - Immutability: Once created, the value of a
Symbol
cannot be changed. - Non-enumerability: Properties keyed by
Symbols
are not included infor...in
loops orObject.keys()
. - Customizing Built-in Behavior: Override default behavior using well-known Symbols like
Symbol.toStringTag
to override the toString method.
const obj = {
[Symbol.toStringTag]: "CustomObject",
name: "Example"
};
console.log(obj.toString()); // "[object CustomObject]"
Global Symbol Registry
Symbols can be registered in a global registry using Symbol.for()
. These are not unique; they can be shared and retrieved globally using the same key.