Tutorials JavaScript Symbol & BigInt
Ch 53 / 78
Chapter 53 Advanced 6 min read JavaScript

Symbol & BigInt

Symbol and BigInt are the two newest JavaScript primitive types — added in ES6 and ES2020 respectively. Symbol creates guaranteed-unique identifiers, perfect for hidden object keys and protocol hooks. BigInt breaks the integer ceiling of Number, letting you work with arbitrarily large whole numbers with full precision — critical for cryptography, finance, and data science.

What you'll learn
What Symbol is and why it guarantees uniqueness
Symbol as unique object property keys
Well-known Symbols: iterator, toPrimitive, hasInstance
Symbol.for() and the global Symbol registry
BigInt syntax, arithmetic, and limitations
When to use BigInt vs Number and mixing pitfalls

Symbol & BigInt — At a Glance

JavaScript has eight data types total. Six are older primitives; Symbol (ES6, 2015) and BigInt (ES2020) are the two newest. Both are primitive values — they are immutable and compared by value, not by reference. But each solves a very different problem.

Symbol
Every Symbol() call returns a 100% unique value — no two Symbols are ever equal. Ideal for private-ish object keys.
BigInt
Integers with no upper limit. Append n to any integer literal — e.g. 9007199254740993n — for exact large-number math.
Well-Known Symbols
Built-in Symbols like Symbol.iterator let you customise how your objects behave with language-level operators.
Real-World Use
Symbols for enum-style constants and hidden properties; BigInt for crypto, precise timestamps, and database IDs.
Type Introduced typeof Primitive? Unique per call?
Symbol() ES6 (2015) "symbol" yes yes
BigInt ES2020 "bigint" yes no
Number ES1 "number" yes no
String ES1 "string" yes no

Symbol — Guaranteed Uniqueness

A Symbol is created by calling Symbol(description). The optional description is purely for debugging — it does not affect uniqueness. Two Symbols with the same description are still completely different values.

Symbol()
Always unique — even same label
Symbol() === Symbol() false
Symbol("id") === Symbol("id") false
typeof Symbol() "symbol"
new Symbol() TypeError!
Symbol("x").toString() "Symbol(x)"
Symbol("x").description "x"
Symbol.for()
Global registry — shared by key
Symbol.for("id") === Symbol.for("id") true
Symbol.for("x") === Symbol("x") false
Symbol.keyFor(Symbol.for("id")) "id"
Symbol.keyFor(Symbol("id")) undefined
Shared across windows/iframes? yes
JavaScript — Symbol Basics
// ── Creating Symbols ──────────────────────────────────────────
const id1 = Symbol(); // no description
const id2 = Symbol("userId"); // with debug label
const id3 = Symbol("userId"); // same label — still different!

id2 === id3; // false — always unique
typeof id2; // "symbol"
id2.description; // "userId"
id2.toString(); // "Symbol(userId)"

// ── Symbol as object property key ────────────────────────────
const SECRET = Symbol("secret");
const user = {
name: "Alice",
[SECRET]: "s3cr3t-token" // computed property key
};

user[SECRET]; // "s3cr3t-token" ✅
user.SECRET; // undefined — dot access won't work

// ── Symbols are NOT enumerable via for..in / Object.keys ─────
Object.keys(user); // ["name"] — SECRET hidden!
for (const k in user) console.log(k); // only "name"

// ── Retrieve Symbol keys explicitly ──────────────────────────
Object.getOwnPropertySymbols(user); // [Symbol(secret)]
Reflect.ownKeys(user); // ["name", Symbol(secret)]
Pro Tip — Symbols ≠ Private
Symbol-keyed properties are not truly private — they can be accessed via Object.getOwnPropertySymbols() or Reflect.ownKeys(). For real private class fields, use the #field syntax introduced in ES2022. Symbols are best for non-colliding keys and well-known protocol hooks.

Well-Known Symbols

JavaScript ships with a set of built-in Symbols stored as static properties on the Symbol constructor. These are called well-known Symbols and they act as hooks — implementing them on your objects lets you customise language-level behaviour like iteration, type coercion, and instanceof checks.

Symbol.iterator
Custom Iteration
Makes any object iterable with for...of, spread [...obj], and destructuring. Must return an iterator object.
obj[Symbol.iterator] = function*()
Symbol.toPrimitive
Type Coercion Hook
Called when the engine needs to coerce your object to a primitive. Receives a hint: "number", "string", or "default".
obj[Symbol.toPrimitive] = (hint) =>
Symbol.hasInstance
instanceof Override
Controls the behaviour of the instanceof operator for a class. Define it as a static method to intercept type checks.
static [Symbol.hasInstance](val)
Symbol.toStringTag
Object.toString() Label
Changes the string returned by Object.prototype.toString. Useful for identifying custom objects in logs and debuggers.
get [Symbol.toStringTag]() { return 'Foo' }
Symbol.asyncIterator
Async Iteration
Powers for await...of loops on your object. Must return an async iterator (object with a next() that returns a Promise).
obj[Symbol.asyncIterator] = async function*()
Symbol.species
Subclass Constructor
Specifies the constructor used to create derived objects in methods like .map() and .filter() on subclasses of Array, Set, or Map.
static get [Symbol.species]() { return Array }
JavaScript — Symbol.iterator in Action
// ── Make a Range object iterable ─────────────────────────────
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}
};

for (const n of range) console.log(n); // 1 2 3 4 5
[...range]; // [1, 2, 3, 4, 5]

// ── Symbol.toPrimitive ────────────────────────────────────────
const money = {
amount: 42,
currency: "USD",
[Symbol.toPrimitive](hint) {
if (hint === "number") return this.amount;
if (hint === "string") return `${this.amount} ${this.currency}`;
return this.amount; // "default"
}
};

+money; // 42 (number hint)
`${money}`; // "42 USD" (string hint)
money + 1; // 43 (default hint → number)

BigInt — Beyond Number.MAX_SAFE_INTEGER

JavaScript's Number type uses 64-bit floating-point (IEEE 754), which can only represent integers exactly up to 253 − 1 (Number.MAX_SAFE_INTEGER = 9007199254740991). Beyond that, precision silently breaks. BigInt removes this ceiling — it stores integers of any size with zero precision loss.

42n
Literal Syntax
Append n to any integer literal to get a BigInt.
typeof 42n → "bigint"
BigInt()
Constructor
Converts a number, string, or boolean to BigInt. Never use new BigInt().
BigInt("99999999999999") → 99999999999999n
+ − * **
Arithmetic
Supports +, −, *, **, % and / (truncates, no decimals).
10n / 3n → 3n (not 3.33)
=== / ==
Comparisons
BigInts can be compared to Numbers with == but not ===. Relational operators work cross-type.
1n === 1 → false | 1n == 1 → true
JavaScript — BigInt Basics
// ── Why Number breaks for large integers ─────────────────────
Number.MAX_SAFE_INTEGER; // 9007199254740991
9007199254740991 + 1; // 9007199254740992 ✅
9007199254740991 + 2; // 9007199254740992 ❌ (wrong!)

// ── BigInt literal: append "n" ────────────────────────────────
const big = 9007199254740991n;
big + 2n; // 9007199254740993n ✅ exact
typeof big; // "bigint"

// ── BigInt() constructor ──────────────────────────────────────
BigInt(42); // 42n
BigInt("12345678901234567890"); // very large n ✅
BigInt(3.14); // RangeError — floats not allowed

// ── Arithmetic ───────────────────────────────────────────────
10n + 3n; // 13n
10n - 3n; // 7n
10n * 3n; // 30n
10n ** 3n; // 1000n
10n / 3n; // 3n ← truncates (no decimal part)
10n % 3n; // 1n

// ── Cannot mix BigInt and Number ─────────────────────────────
10n + 5; // TypeError! Must be same type
Number(10n) + 5; // 15 — convert first ✅
10n + BigInt(5); // 15n ✅
Operation Example Result Notes
+ 5n + 3n 8n Both must be BigInt
/ 10n / 3n 3n Truncates — no decimals
** 2n ** 64n 18446744073709551616n Exact — no precision loss
=== 1n === 1 false Different types
== 1n == 1 true Loose coercion
< 1n < 2 true Cross-type relational works
Math.* Math.sqrt(4n) TypeError Math methods don't accept BigInt
JSON JSON.stringify(1n) TypeError Not serialisable by default

Symbol.for() — The Global Registry

Normal Symbol() calls always produce a brand-new value. But sometimes you need the same Symbol to be shared across modules, iframes, or service workers. Symbol.for(key) maintains a global registry: the first call creates and registers the Symbol; subsequent calls with the same key return the exact same Symbol.

JavaScript — Symbol.for() & Symbol.keyFor()
// ── Symbol() vs Symbol.for() ─────────────────────────────────
const s1 = Symbol("shared"); // local — always new
const s2 = Symbol("shared"); // different from s1
s1 === s2; // false

const g1 = Symbol.for("shared"); // creates + registers
const g2 = Symbol.for("shared"); // fetches same from registry
g1 === g2; // true ✅

// ── Retrieve the key from a registered Symbol ────────────────
Symbol.keyFor(g1); // "shared"
Symbol.keyFor(s1); // undefined — not in registry

// ── Practical use: cross-module enum ─────────────────────────
// moduleA.js
export const STATUS_OK = Symbol.for("app.status.ok");

// moduleB.js — same Symbol, no import needed
const ok = Symbol.for("app.status.ok");
ok === STATUS_OK; // true ✅
Global Registry Pitfall
Because Symbol.for() keys are global (shared across realms including iframes and Node.js vm contexts), namespace your keys with a prefix like "mylib.featureName" to avoid accidental collisions with third-party libraries.

Try It — Live Editor

Experiment with Symbol uniqueness and BigInt arithmetic in the editor below. Try changing descriptions, compare cross-type, or push BigInt beyond Number.MAX_SAFE_INTEGER to see exact results.

Live Editor
✎ Editor
👁 Preview

Common Patterns & Recipes

These real-world patterns will help you apply Symbol and BigInt effectively in production JavaScript code.

JavaScript — Symbol & BigInt Recipes
// ── 1. Symbol-based enum (collision-safe constants) ──────────
const Direction = Object.freeze({
UP: Symbol("UP"),
DOWN: Symbol("DOWN"),
LEFT: Symbol("LEFT"),
RIGHT: Symbol("RIGHT"),
});
function move(dir) {
if (dir === Direction.UP) console.log("Moving up");
}
move(Direction.UP); // ✅ safe — no string collision possible

// ── 2. Symbol to tag object metadata ─────────────────────────
const TYPE = Symbol("type");
const order = { id: 1, [TYPE]: "Order" };
order[TYPE]; // "Order" — hidden from JSON.stringify
JSON.stringify(order); // '{"id":1}' — Symbol keys skipped

// ── 3. BigInt for safe database IDs ─────────────────────────
const userId = BigInt("18446744073709551615"); // uint64 max
userId + 1n; // 18446744073709551616n ✅

// ── 4. BigInt modulo for cryptographic operations ────────────
function modPow(base, exp, mod) { // fast modular exponentiation
let result = 1n;
base = base % mod;
while (exp > 0n) {
if (exp % 2n === 1n) result = (result * base) % mod;
exp = exp / 2n;
base = (base * base) % mod;
}
return result;
}
modPow(2n, 10n, 1000n); // 24n

// ── 5. Safe BigInt JSON serialise workaround ─────────────────
JSON.stringify({ val: 42n },
(k, v) => typeof v === "bigint" ? v.toString() : v
); // '{"val":"42"}'
Quick Check
What does Symbol("id") === Symbol("id") return?
Quick Check
What is the result of 10n / 3n in JavaScript?
Quick Check
Which of the following is true about Symbol-keyed properties?
Chapter Summary
  • Symbol is a primitive type (ES6) that creates guaranteed-unique values. Two Symbol() calls always produce different identities, even with the same description string.
  • Symbols are ideal as non-colliding object property keys. They are skipped by for...in, Object.keys(), and JSON.stringify(), but are retrievable via Object.getOwnPropertySymbols().
  • Symbol.for(key) creates a global registry Symbol that is shared across modules and iframes. Use Symbol.keyFor(sym) to look up its key.
  • Well-known Symbols like Symbol.iterator, Symbol.toPrimitive, and Symbol.hasInstance let you hook into JavaScript's built-in protocols and customise object behaviour.
  • BigInt (ES2020) removes the integer precision ceiling of Number. Append n to any integer literal or call BigInt(value) to create one.
  • BigInt supports +, -, *, **, %, and / (division truncates — no decimals). You cannot mix BigInt and Number in arithmetic — convert explicitly.
  • 1n === 1 is false (different types), but 1n == 1 is true (loose coercion). Relational operators work cross-type.
  • Math.* methods and JSON.stringify() do not support BigInt. Provide a replacer function or convert to string before serialising.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel