Symbol?Symbol is a primitive data type introduced in ES6.
Its biggest feature is uniqueness.
Every symbol value is distinct.
const a = Symbol("id");const b = Symbol("id");
console.log(a === b); // falseSymbol is useful when you need:
const id = Symbol("id");The description is only for debugging and readability.
Symbol.for()Symbol.for() uses the global symbol registry.
const a = Symbol.for("token");const b = Symbol.for("token");
console.log(a === b); // trueSymbolEach normal Symbol() call creates a unique value.
A symbol is a primitive value and cannot be changed.
const id = Symbol("id");// "value: " + id // TypeErrorUse String(id) if needed.
Symbol as Object Propertiesconst id = Symbol("id");
const user = { name: "Tom", [id]: 123,};Symbol-keyed properties are not included in normal for...in or Object.keys.
const id = Symbol("id");const user = { name: "Tom", [id]: 123 };
console.log(Object.keys(user)); // ["name"]console.log(Object.getOwnPropertySymbols(user)); // [Symbol(id)]JavaScript provides several built-in symbols for custom behavior.
Symbol.iteratorUsed to define iteration behavior.
const collection = { data: [1, 2, 3], [Symbol.iterator]() { return this.data[Symbol.iterator](); },};Symbol.toStringTagControls the tag shown by Object.prototype.toString.
const obj = { [Symbol.toStringTag]: "CustomObject",};
console.log(Object.prototype.toString.call(obj));// [object CustomObject]Symbol.hasInstanceCan customize instanceof behavior.
Useful in libraries or shared code.
const STATUS = { PENDING: Symbol("pending"), DONE: Symbol("done"),};It is not true privacy, but it can reduce accidental access.
Symbol values are ignored by JSON serialization.
Descriptions help when reading logs and devtools output.
Use Symbol for semantic uniqueness, not because it is automatically faster.
Symbol is most useful when you need a unique identifier or want to customize object behavior in advanced ways.
It is not used in every project, but it is an important modern JavaScript feature.