What Is 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); // false

Why Do We Need It?

Symbol is useful when you need:

  • unique property keys
  • to avoid naming collisions
  • some forms of meta-programming

Creating Symbols

Basic creation

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); // true

Characteristics of Symbol

Uniqueness

Each normal Symbol() call creates a unique value.

Immutability

A symbol is a primitive value and cannot be changed.

No implicit string conversion

const id = Symbol("id");
// "value: " + id // TypeError

Use String(id) if needed.

Using Symbol as Object Properties

Basic usage

const id = Symbol("id");
const user = {
name: "Tom",
[id]: 123,
};

Non-enumerability in common loops

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)]

Built-in Symbols

JavaScript provides several built-in symbols for custom behavior.

Symbol.iterator

Used to define iteration behavior.

const collection = {
data: [1, 2, 3],
[Symbol.iterator]() {
return this.data[Symbol.iterator]();
},
};

Symbol.toStringTag

Controls the tag shown by Object.prototype.toString.

const obj = {
[Symbol.toStringTag]: "CustomObject",
};
console.log(Object.prototype.toString.call(obj));
// [object CustomObject]

Symbol.hasInstance

Can customize instanceof behavior.

Practical Uses

1. Avoid property name collisions

Useful in libraries or shared code.

2. Create enum-like values

const STATUS = {
PENDING: Symbol("pending"),
DONE: Symbol("done"),
};

3. Simulate private-like fields

It is not true privacy, but it can reduce accidental access.

Notes and Best Practices

JSON serialization

Symbol values are ignored by JSON serialization.

Debugging

Descriptions help when reading logs and devtools output.

Performance

Use Symbol for semantic uniqueness, not because it is automatically faster.

Summary

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.