Ankaj Gupta
August 20, 2020

Javascript division by 0

JavaScript Basics

What Happens When You Divide by Zero in JavaScript?

Unlike many languages that throw an error, JavaScript returns special numeric values when you divide by zero. Understanding these edge cases prevents confusing console output and logical bugs in your applications.

Safe but Special

Dividing a finite non-zero number by zero never throws an exception in JavaScript. The runtime returns Infinity or -Infinity instead.

Watch for NaN

Zero divided by zero—or an invalid numeric expression—produces NaN. Always guard calculations with sanity checks.

Division by Zero Outcomes

Expression Result Explanation
10 / 0 Infinity Positive numerator divided by zero returns positive infinity.
-10 / 0 -Infinity Sign is preserved—negative numerator produces negative infinity.
0 / 0 NaN Mathematically undefined, so JavaScript returns Not-a-Number.
1 / Infinity 0 When dividing by infinity you approach zero, which is useful for normalization logic.

Console Examples

Positive Numerator

const numerator = 10;
const denominator = 0;

const result = numerator / denominator;
console.log(result); // Infinity
console.log(Number.isFinite(result)); // false

Zero Numerator

const value = 0 / 0;

console.log(value);             // NaN
console.log(Number.isNaN(value)); // true
console.log(value === value);     // false (NaN is never equal to itself)

How to Guard Against Unexpected Results

  • Check denominators first: if (denominator === 0) before performing the division.
  • Use helper utilities: Create a reusable function that returns null or throws when division is invalid.
  • Normalize Infinity: Replace Infinity with a sentinel value when serializing or persisting data.
  • Avoid NaN propagation: NaN contaminates further calculations—use Number.isNaN() to guard intermediate values.

Reusable Safe Division Helper

export function safeDivide(numerator, denominator, fallback = null) {
    if (denominator === 0) {
        return fallback;
    }

    const value = numerator / denominator;
    return Number.isFinite(value) ? value : fallback;
}

// usage
console.log(safeDivide(12, 3)); // 4
console.log(safeDivide(12, 0)); // null

Key Takeaways

  • JavaScript returns Infinity or -Infinity instead of throwing when dividing by zero.
  • 0 / 0 is NaN, which silently poisons later math operations.
  • Always validate denominators and handle special numeric values before rendering or storing results.
Code JavaScript Code

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts