Lesson 11: Mastering JavaScript Symbols

manoj ymkmanoj ymk
4 min read

🔹 What is a Symbol?

  • A Symbol is a primitive data type.

  • It’s created using the Symbol() function.

  • Each Symbol is completely unique, even if you give it the same description.

✅ Syntax:

const sym1 = Symbol();
const sym2 = Symbol("desc");
const sym3 = Symbol("desc");

console.log(sym2 === sym3); // false

Even though sym2 and sym3 have the same description ("desc"), they are not equal. That's the magic—uniqueness is guaranteed.


🔍 Why Symbols? What Problem Do They Solve?

Symbols solve the problem of unintentional property name collisions in objects—especially useful when you're working with external libraries, frameworks, or when augmenting existing objects.

🧠 Real-World Problem:

Imagine two libraries add a toString method to the same object:

obj.toString = function() { return 'Lib A'; }
// Lib B overrides it
obj.toString = function() { return 'Lib B'; }

🙁 Clash.

But with Symbols, you can do:

const toStrA = Symbol('toString');
const toStrB = Symbol('toString');

obj[toStrA] = function() { return 'Lib A'; }
obj[toStrB] = function() { return 'Lib B'; }

Now, no conflicts—each library has its own unique key.


💡 Characteristics of Symbols

FeatureDescription
Primitive?✅ Yes
Unique?✅ Always unique
Hidden in for...in?✅ Yes
Coercible to string?❌ No, throws error if you try
Description useful?✅ Helps in debugging
Used in Object keys?✅ Perfect for that

🚧 You cannot implicitly convert Symbol to string

const sym = Symbol("id");
console.log("ID: " + sym); // ❌ TypeError

✅ Correct way:

console.log("ID: " + sym.toString());

🔐 Symbols as Object Keys

Symbols make great private keys (pseudo-private at least):

const secret = Symbol("secret");

const user = {
  name: "Alice",
  [secret]: "hiddenValue"
};

console.log(user.secret); // undefined
console.log(user[secret]); // "hiddenValue"
  • Not accessible through dot notation.

  • Not included in for...in, Object.keys(), Object.getOwnPropertyNames().

To get all Symbol keys:

Object.getOwnPropertySymbols(user); // [Symbol(secret)]

🌐 Global Symbol Registry (Symbol.for)

Most Symbols are local and unique, but you can also store Symbols globally using Symbol.for():

const sym1 = Symbol.for("app.id");
const sym2 = Symbol.for("app.id");

console.log(sym1 === sym2); // ✅ true
  • Symbol.for(key) uses a global symbol registry.

  • If a symbol with the given key exists, it's returned.

  • Otherwise, a new one is created.

➡️ Use case: Sharing keys across different parts/modules of an app.

To retrieve key:

Symbol.keyFor(sym1); // "app.id"

📦 Built-in Symbols

JavaScript provides some built-in symbols for internal behavior customization:

SymbolPurpose
Symbol.iteratorMakes objects iterable
Symbol.toPrimitiveCustom conversion to primitives
Symbol.toStringTagCustomize Object.prototype.toString.call(obj)
Symbol.hasInstanceCustomizes instanceof behavior
Symbol.isConcatSpreadableControl how arrays or array-like objects spread
Symbol.match / replaceControl how objects behave in regex ops

Example:

const person = {
  [Symbol.toPrimitive](hint) {
    return hint === "string" ? "Person" : 42;
  }
};

console.log(`${person}`); // "Person"
console.log(+person);     // 42

⚔️ Interview Questions You Might Face

  1. Why are Symbols useful in object properties?

  2. How does Symbol uniqueness work?

  3. Difference between Symbol() and Symbol.for()?

  4. How do you retrieve all Symbol keys of an object?

  5. What happens if you try to + a Symbol to a string?


🛠️ Mnemonics & Tips

  • S for Symbol, S for Secret – Use Symbols for semi-hidden or internal properties.

  • Symbol.for = Shared Symbol.

  • Symbols hide from most object introspection—they’re stealthy keys!


🔚 Summary

FeatureSymbol
Unique?✅ Always unique
Primitive?✅ Yes
Use caseObject keys, hidden/internal props
VisibilityNot in for...in or Object.keys()
Global sharingUse Symbol.for()
Debug descriptionOptional, used in Symbol("desc")
0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk