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.
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.
n to any
integer literal — e.g. 9007199254740993n — for exact large-number
math.Symbol.iterator let you
customise how your objects behave with language-level operators.| 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.
// ── 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)]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.
for...of, spread
[...obj], and destructuring. Must return an iterator object.
"number", "string", or
"default".
instanceof operator
for a class. Define it as a static method to intercept type checks.Object.prototype.toString.
Useful for identifying custom objects in logs and debuggers.
for await...of loops on your object. Must
return an async iterator (object with a next() that returns a
Promise)..map() and .filter() on subclasses of
Array, Set, or Map.// ── 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.
n to any integer literal to get a BigInt.new BigInt().
// ── 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.
// ── 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 ✅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.
Common Patterns & Recipes
These real-world patterns will help you apply Symbol and BigInt effectively in production JavaScript code.
// ── 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"}'Symbol("id") === Symbol("id") return?10n / 3n in JavaScript?- 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(), andJSON.stringify(), but are retrievable viaObject.getOwnPropertySymbols(). Symbol.for(key)creates a global registry Symbol that is shared across modules and iframes. UseSymbol.keyFor(sym)to look up its key.- Well-known Symbols like
Symbol.iterator,Symbol.toPrimitive, andSymbol.hasInstancelet you hook into JavaScript's built-in protocols and customise object behaviour. - BigInt (ES2020) removes the integer precision ceiling of
Number. Appendnto any integer literal or callBigInt(value)to create one. - BigInt supports
+,-,*,**,%, and/(division truncates — no decimals). You cannot mix BigInt and Number in arithmetic — convert explicitly. 1n === 1isfalse(different types), but1n == 1istrue(loose coercion). Relational operators work cross-type.Math.*methods andJSON.stringify()do not support BigInt. Provide a replacer function or convert to string before serialising.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.