Skip to content

Division by Zero

Quick summary

You divided by zero — the result is undefined mathematically and causes Infinity (JavaScript), ZeroDivisionError (Python), or a crash.

Why this happens

  • A variable used as a divisor is 0 and was not checked

  • User input or API data provided 0 as a denominator

  • A calculation that can produce 0 was not guarded

Minimal example

✗ Broken code
function percentage(part, total) {
  return (part / total) * 100;
}
console.log(percentage(50, 0)); // Infinity
✓ Fixed code
function percentage(part, total) {
  if (total === 0) return 0;
  return (part / total) * 100;
}
console.log(percentage(50, 0)); // 0

When total is 0, the division produces Infinity. Adding a guard check returns 0 instead, which is a safe default.

How to diagnose

  • Check the value of the divisor before the division

  • Look for Infinity or NaN in the output, which indicates division by zero

  • Trace where the divisor value comes from

How to fix

  • Add a check: if (divisor !== 0) result = numerator / divisor

  • Return a default value or error message when the divisor is 0

  • Use a try/catch or conditional to handle the special case

How to prevent

  • Always validate divisors before dividing

  • Add unit tests that include zero as a divisor

Related Resources

Related Glossary

Related Lessons

← Back to language