Division or Modulo by Zero

ID

javascript.division_by_zero

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

arithmetic, reliability

Description

Reports division (/) or modulo (%) operations whose right-hand side is the literal 0 (or 0.0, 0n).

Rationale

JavaScript handles division by zero in three different ways depending on operand types, and none of them are usually what the author meant:

  • n / 0 returns Infinity (or -Infinity, or NaN if n is 0).

  • n % 0 returns NaN.

  • bigint / 0n and bigint % 0n throw a RangeError at runtime.

In every case the program continues with a non-finite value or an unhandled exception, often surfacing far from the offending divide as NaN propagation or a confusing stack trace.

// Bad
const rate = total / 0;          // Infinity
const rem  = value % 0;          // NaN
const big  = 10n / 0n;           // throws RangeError

Remediation

Guard the divisor or compute it from a value that cannot be zero:

// Good
const rate = count === 0 ? 0 : total / count;
const rem  = divisor === 0 ? 0 : value % divisor;

If the literal zero was intended as a placeholder during development, replace it with the real divisor before committing.