Skip to content

Integer Overflow

Quick summary

Your calculation exceeded the maximum value the number type can hold, producing an unexpected result.

Why this happens

  • Multiplying or exponentiating large numbers

  • Accumulating values in a loop without bounds

  • Factorial or Fibonacci of large inputs

Minimal example

✗ Broken code
console.log(2 ** 53 + 1 === 2 ** 53); // true — precision lost!
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
✓ Fixed code
console.log(BigInt(2) ** BigInt(53) + BigInt(1) === BigInt(2) ** BigInt(53)); // false
console.log(2n ** 53n + 1n); // 9007199254740993n (exact)

JavaScript numbers lose precision above 2^53. 2^53 + 1 equals 2^53 due to rounding. Using BigInt preserves exact integer values regardless of size.

How to diagnose

  • Check if the result is Infinity, negative, or unexpectedly small

  • Compare the result with Number.MAX_SAFE_INTEGER

  • Log intermediate values to find where the overflow occurs

How to fix

  • Use BigInt for arbitrarily large integers in JavaScript

  • Use modular arithmetic to keep numbers bounded

  • Validate inputs to prevent overflow before it happens

How to prevent

  • Use BigInt when working with very large numbers

  • Validate inputs to keep calculations within safe ranges

Related Resources

Related Glossary

Related Lessons

← Back to language