Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 156 ยท Data Types

BigInt and Symbol

Meet JavaScript's two newest primitives. Use BigInt for integers beyond the safe limit and Symbol for unique keys, plus a quick look at well-known symbols.

You have met five of JavaScript's primitive types already: string, number, boolean, null and undefined. Two more complete the set, both added in modern versions of the language: BigInt, for whole numbers too large for a normal number, and Symbol, for values that are guaranteed to be unique.

You won't use either of them in every program. BigInt shows up when you deal with very large IDs, cryptography or exact money math in the smallest unit; symbols mostly appear inside libraries and in the language's own machinery. But both have clear jobs, and knowing them means nothing in a typeof check or a codebase will surprise you.

Why BigInt exists

Regular JavaScript numbers are 64-bit floating-point values. They can store huge magnitudes, but they can only represent whole numbers exactly up to 253 โˆ’ 1 โ€” that's 9,007,199,254,740,991. JavaScript exposes this limit as Number.MAX_SAFE_INTEGER. Beyond it, integers start to lose precision:

JS Past the safe integer limit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

max + 2 prints the same value as max + 1, and the long ID is silently rounded. For counting things in a typical app that's never an issue โ€” but for database IDs from some systems, timestamps in nanoseconds, or big factorials, it's a real bug.

Creating BigInts

A BigInt is an integer of arbitrary size, limited only by memory. Create one by adding n to the end of an integer literal, or by calling BigInt():

JS BigInt basics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

BigInts support +, -, *, ** and % as usual. Division / drops the fractional part, because a BigInt can only hold whole numbers. The console marks BigInts with a trailing n so you can tell them apart from numbers.

When converting from data, prefer passing a string to BigInt(). Writing BigInt(1234567890123456789) would first create a regular number โ€” already rounded โ€” and convert that rounded value.

BigInt rules and limits

BigInt is deliberately strict about mixing with regular numbers, because silently converting could lose precision:

JS Mixing BigInt and Number

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The main rules:

  • No mixing in arithmetic. 10n + 5 throws a TypeError. Convert one side with BigInt() or Number().
  • Comparisons work across types: <, > and == compare values, while === is false because the types differ.
  • No Math methods and no unary plus (+10n throws).
  • Truthiness: 0n is falsy, every other BigInt is truthy.
  • JSON can't store them. JSON.stringify({ id: 1n }) throws; convert BigInts to strings first.
  • No decimals. BigInt is for integers. It isn't a decimal type, so it won't fix 0.1 + 0.2 โ€” for money you'd store whole cents (1999n) instead.

BigInt is also slower than regular numbers, so use it only when you actually need values beyond the safe range. It has been supported in all major browsers and Node.js since around 2020.

Symbols: unique values

A Symbol is a value that is unique: no two symbols are ever equal, even if you create them with the same description.

JS Every symbol is unique

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The text you pass to Symbol() is just a description for debugging โ€” it doesn't make the symbol findable or equal to anything. Note also that Symbol() is called without new, and that symbols refuse implicit string conversion; use .description or String(sym) when you need text.

Symbols as property keys

The main use of symbols is as object property keys that can't clash with any other key. Imagine you're attaching extra data to objects that belong to someone else's code. If you used a string key like "id", you might overwrite their id. A symbol key can never collide:

JS Symbol keys don't collide

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You read and write symbol keys with square brackets, obj[sym]. The square brackets in the object literal, [internalId]: โ€ฆ, are a computed key, covered in Objects.

Symbol-keyed properties are skipped by Object.keys(), for...in and JSON.stringify(), so they stay out of the way. They are not private, though: Object.getOwnPropertySymbols() lists them. For real privacy, classes have #private fields, covered in Private Fields and Static Members.

A practical tip: store each symbol in a variable (or export it from a module) and reuse that variable everywhere. Since a fresh Symbol("internalId") is a different key, code that doesn't have access to your variable simply can't reach the property by accident.

Shared symbols with Symbol.for()

Sometimes separate parts of a program need the same symbol. Symbol.for(key) looks the key up in a global registry and returns the same symbol every time:

JavaScript
Symbol.for("app.theme") === Symbol.for("app.theme");  // true
Symbol("app.theme") === Symbol("app.theme");          // false

The reverse lookup is Symbol.keyFor(symbol). It returns the registry key of a symbol made with Symbol.for(), and undefined for any other symbol, including the well-known ones:

JavaScript
const shared = Symbol.for("app.id");
Symbol.keyFor(shared);            // "app.id"
Symbol.keyFor(Symbol("x"));       // undefined (not in the registry)
Symbol.keyFor(Symbol.iterator);   // undefined

Well-known symbols (a brief look)

JavaScript itself uses a set of built-in symbols, called well-known symbols, as hooks into the language. They live as properties on Symbol, such as Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag and Symbol.asyncIterator. When you give an object a method under one of these keys, built-in operations start using it.

For example, Symbol.iterator is what makes arrays, strings, Maps and Sets work with for...of and the spread operator. Symbol.toStringTag changes the label in [object โ€ฆ]:

JavaScript
const sensor = {
  [Symbol.toStringTag]: "Sensor",
};

String(sensor); // "[object Sensor]"

Because these keys are symbols rather than strings, adding them could never break older code that happened to use a property named "iterator". That's exactly why the language designers chose symbols. You'll put Symbol.iterator to real use in Iterators and Generators.

Customizing built-in behavior

Here are the well-known symbols you are most likely to use, beyond Symbol.iterator:

Symbol Hooks into You define
Symbol.hasInstance x instanceof C a static method on C returning a boolean
Symbol.toPrimitive conversion to number, string or default a method receiving the hint "number", "string" or "default"
Symbol.toStringTag Object.prototype.toString a string (or getter) used in [object โ€ฆ]
Symbol.isConcatSpreadable Array.prototype.concat a boolean saying whether to spread the value
Symbol.species which constructor array methods like map use for results a static getter on a subclass
Symbol.asyncIterator for await...of an async generator or method returning an async iterator
Symbol.match, replace, search, split the matching string methods methods that make an object behave like a regex
JS Well-known symbols at work

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Without Symbol.species, stack.map() would create another Stack through the subclass constructor. Overriding it is rare, but it is the reason built-in methods behave well with subclasses. Symbol.hasInstance and Symbol.toPrimitive are the two you may genuinely reach for. Use them sparingly: code that changes how instanceof or + works is surprising to readers. Iterators and Generators covers Symbol.iterator and Symbol.asyncIterator in depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does typeof 10n return?

    BigInt is its own primitive type, reported as "bigint".
  2. 2. What happens with 5n + 1?

    BigInt and Number can't be mixed in arithmetic. Convert one side explicitly, e.g. 5n + BigInt(1).
  3. 3. What is 7n / 2n?

    BigInts are whole numbers, so division drops the fractional part (rounding toward zero).
  4. 4. What does Symbol("x") === Symbol("x") evaluate to?

    The description is only a label. Use Symbol.for("x") if you need the same symbol in two places.
  5. 5. Which call lists an object's symbol-keyed properties?

    Symbol keys are skipped by Object.keys, Object.values and JSON, but Object.getOwnPropertySymbols returns them.

Summary

  • Numbers represent integers exactly only up to Number.MAX_SAFE_INTEGER (253 โˆ’ 1).
  • BigInt (123n, BigInt("123")) holds integers of any size; division drops fractions.
  • BigInt and Number can't be mixed in arithmetic, Math doesn't accept BigInts, and JSON can't store them.
  • Symbol("label") creates a unique value; symbols make collision-free, non-enumerated (but not private) property keys.
  • Symbol.for() shares symbols through a registry; well-known symbols like Symbol.iterator, hasInstance, toPrimitive and species hook into built-in behavior, and Symbol.keyFor() reads a shared symbol's key.

Next: Arithmetic and Assignment Operators โ€” doing math, counting up and updating variables in place.