Computing zeroes (solutions) of a mathematical equation in JavaScript

We are required to write a JavaScript function that takes in three numbers representing the coefficients of a quadratic equation (ax² + bx + c = 0). The function should find the real roots of the equation or return false if the roots are complex (non-real).

A quadratic equation has real roots when its discriminant (b² - 4ac) is greater than or equal to zero. The roots are calculated using the quadratic formula: x = (-b ± ?discriminant) / (2a).

Syntax

// Quadratic formula: x = (-b ± ?(b² - 4ac)) / (2a)
// Discriminant = b² - 4ac

Example

Here's a complete implementation that finds the roots of a quadratic equation:

const coeff = [1, 12, 3];

const findRoots = co => {
    const [a, b, c] = co;
    const discriminant = (b * b) - 4 * a * c;
    
    // Check for non-real roots
    if(discriminant < 0){
        return false;
    };
    
    const d = Math.sqrt(discriminant);
    const x1 = (-b + d) / (2 * a);
    const x2 = (-b - d) / (2 * a);
    
    return [x1, x2];
};

console.log(findRoots(coeff));

Output

[ -0.2554373534619714, -11.744562646538029 ]

Testing Different Cases

Let's test the function with different types of quadratic equations:

// Case 1: Two distinct real roots
console.log("Case 1 - Two distinct roots:");
console.log(findRoots([1, -5, 6])); // x² - 5x + 6 = 0

// Case 2: One repeated root (discriminant = 0)
console.log("\nCase 2 - One repeated root:");
console.log(findRoots([1, -4, 4])); // x² - 4x + 4 = 0

// Case 3: No real roots (discriminant < 0)
console.log("\nCase 3 - No real roots:");
console.log(findRoots([1, 2, 5])); // x² + 2x + 5 = 0
Case 1 - Two distinct roots:
[ 3, 2 ]

Case 2 - One repeated root:
[ 2, 2 ]

Case 3 - No real roots:
false

How It Works

The algorithm follows these steps:

  1. Extract coefficients: Destructure the array to get a, b, and c values
  2. Calculate discriminant: Use the formula b² - 4ac
  3. Check validity: If discriminant
  4. Apply quadratic formula: Calculate both roots using (-b ± ?discriminant) / (2a)
  5. Return results: Return an array containing both roots

Key Points

  • When discriminant > 0: Two distinct real roots
  • When discriminant = 0: One repeated real root
  • When discriminant
  • The function handles edge cases by returning false for complex roots

Conclusion

This JavaScript function efficiently computes the real roots of quadratic equations using the quadratic formula. It properly handles all cases including distinct roots, repeated roots, and complex roots by returning false when no real solutions exist.

Updated on: 2026-03-15T23:19:00+05:30

146 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements