Solving a Quadratic Equation in JavaScript Made Easy

Hey there, budding coders! Today, we’re diving into the fascinating world of quadratic equations—don’t worry, it’s not as intimidating as it sounds. Whether you’ve encountered them in math class or just heard them in passing, quadratic equations pop up in various real-world scenarios, from physics to finance. The good news is, you can solve these using JavaScript! In this blog, we’ll break down the essentials of a quadratic equation and show you how to tackle it programmatically in JavaScript. So, grab a cup of chai and let’s explore the magic of the Quadratic Equation in JavaScript together!

Quadratic Equation in JavaScript- Code

// Function to solve the quadratic equation ax^2 + bx + c = 0
function solveQuadratic(a, b, c) {
    let discriminant = b * b - 4 * a * c;  // Calculate the discriminant
    let roots = {}; // Object to store the roots

    if (discriminant > 0) {
        // Two real and distinct roots
        roots.x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        roots.x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
    } else if (discriminant === 0) {
        // One real root (both roots are the same)
        roots.x1 = roots.x2 = -b / (2 * a);
    } else {
        // Two complex roots
        roots.x1 = (-b / (2 * a)).toFixed(2) + " + " + (Math.sqrt(-discriminant) / (2 * a)).toFixed(2) + "i";
        roots.x2 = (-b / (2 * a)).toFixed(2) + " - " + (Math.sqrt(-discriminant) / (2 * a)).toFixed(2) + "i";
    }

    return roots;
}

// Test cases
console.log(solveQuadratic(1, -3, 2));  // Output: {x1: 2, x2: 1}
console.log(solveQuadratic(1, 2, 1));   // Output: {x1: -1, x2: -1}
console.log(solveQuadratic(1, 1, 1));   // Output: {x1: "-0.50 + 0.87i", x2: "-0.50 - 0.87i"}

  

Explanation of the Code

The provided code defines a JavaScript function solveQuadratic(a, b, c) that calculates the roots of a quadratic equation in the form:ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0

Where:

  • aaa, bbb, and ccc are the coefficients of the quadratic equation.
  • The roots of the quadratic equation are calculated using the quadratic formula:

x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 – 4ac}}{2a}x=2a−b±b2−4ac​​

This formula has three possible cases depending on the discriminant (Δ=b2−4ac\Delta = b^2 – 4acΔ=b2−4ac):

  1. If discriminant > 0: The quadratic equation has two distinct real roots.
  2. If discriminant = 0: The equation has one real root (both roots are the same).
  3. If discriminant < 0: The equation has two complex conjugate roots (imaginary roots).

Output and Explanation of Each Test Case

Output: {x1: "-0.50 + 0.87i", x2: "-0.50 - 0.87i"}

Test Case 1: solveQuadratic(1, -3, 2)

Coefficients: a=1a = 1a=1, b=−3b = -3b=−3, c=2c = 2c=2

Discriminant: Δ=(−3)2−4(1)(2)=9−8=1\Delta = (-3)^2 – 4(1)(2) = 9 – 8 = 1Δ=(−3)2−4(1)(2)=9−8=1 (positive discriminant)

Roots: x1=−(−3)+12(1)=3+12=2x_1 = \frac{-(-3) + \sqrt{1}}{2(1)} = \frac{3 + 1}{2} = 2×1​=2(1)−(−3)+1​​=23+1​=2 x2=−(−3)−12(1)=3−12=1x_2 = \frac{-(-3) – \sqrt{1}}{2(1)} = \frac{3 – 1}{2} = 1×2​=2(1)−(−3)−1​​=23−1​=1

Output: {x1: 2, x2: 1}

Test Case 2: solveQuadratic(1, 2, 1)

Coefficients: a=1a = 1a=1, b=2b = 2b=2, c=1c = 1c=1

Discriminant: Δ=(2)2−4(1)(1)=4−4=0\Delta = (2)^2 – 4(1)(1) = 4 – 4 = 0Δ=(2)2−4(1)(1)=4−4=0 (zero discriminant)

Roots: x1=x2=−22(1)=−1x_1 = x_2 = \frac{-2}{2(1)} = -1×1​=x2​=2(1)−2​=−1

Output: {x1: -1, x2: -1}

Test Case 3: solveQuadratic(1, 1, 1)

Coefficients: a=1a = 1a=1, b=1b = 1b=1, c=1c = 1c=1

Discriminant: Δ=(1)2−4(1)(1)=1−4=−3\Delta = (1)^2 – 4(1)(1) = 1 – 4 = -3Δ=(1)2−4(1)(1)=1−4=−3 (negative discriminant)

Roots (complex): x1=−12(1)+i⋅32(1)=−0.50+0.87ix_1 = \frac{-1}{2(1)} + i \cdot \frac{\sqrt{3}}{2(1)} = -0.50 + 0.87ix1​=2(1)−1​+i⋅2(1)3​​=−0.50+0.87i x2=−12(1)−i⋅32(1)=−0.50−0.87ix_2 = \frac{-1}{2(1)} – i \cdot \frac{\sqrt{3}}{2(1)} = -0.50 – 0.87ix2​=2(1)−1​−i⋅2(1)3​​=−0.50−0.87i

Output

{ x1: 2, x2: 1 }
{ x1: -1, x2: -1 }
{ x1: "-0.50 + 0.87i", x2: "-0.50 - 0.87i" }

Real-Life Uses of Quadratic Equation in JavaScript

Some practical use cases of ‘Quadratic Equation in JavaScript’. Understanding these real-world applications will help you see how these mathematical formulas aren’t just number-crunching exercises but have real utility in various fields. Here’s how:

  1. Projectile Motion in Sports: Ever wondered how cricketers judge where a ball will land after being hit? In sports analytics, quadratic equations help calculate an object’s trajectory in the air. By using ‘Quadratic Equation in JavaScript’, analysts predict where a cricket ball or a football will land based on its initial velocity and angle.
  2. Modeling Physics in Games: If you’re a gaming enthusiast, this will sound familiar. Video games often simulate real-world physics, like how a character jumps over obstacles. JavaScript uses quadratic equations to animate these parabolic motions that occur when forces, like gravity, act upon characters.
  3. Architectural Design: Architects use quadratic equations to design arches and bridges. By applying these equations in JavaScript, they can visualize and adjust forms before any construction begins, ensuring stability and aesthetic appeal without compromising on safety.
  4. Financial Calculations: Quadratic equations are also applied in calculating certain types of loans in the financial sector. For instance, the equations can determine when an investment will yield a certain profit, which is modeled using JavaScript on financial software for ease and precision.
  5. Computer Graphics: When designing computer graphics, quadratic equations create curves and patterns that appear visually pleasing. A software engineer might use ‘Quadratic Equation in JavaScript’ to draw complex shapes, enhancing the visual experience in digital artwork.

        These examples illustrate that quadratic equations aren’t confined to textbooks; they’re a key player in both practical problem-solving and innovation across diverse applications! The beauty of using them in JavaScript lies in its simplicity and flexibility, making it an ideal choice for beginners and professionals alike.

          Common Interview Questions on Quadratic Equation in JavaScript

          1. What is the purpose of the quadratic formula in JavaScript?
            The formula helps to find the roots of a quadratic equation using JavaScript.
          2. How do you handle negative discriminants in JavaScript?
            Return a statement indicating “No Real Roots” when the discriminant is below zero.
          3. Why is the discriminant important in solving quadratic equations?
            It determines the nature of the roots (real, repeated, or imaginary).
          4. Can you describe how to implement complex roots in JavaScript?
            Use complex libraries or math functions to handle imaginary components.
          5. What is the impact of large coefficients on the program’s performance?
            Large numbers can lead to precision errors; consider handling them carefully.

          Our AI-powered js online compiler lets users instantly write, run, and test code, making learning JavaScript seamless. With AI assistance, coding becomes intuitive and efficient, helping users understand concepts faster while providing a friendly environment for beginners to experiment and grow.

          Conclusion

          Mastering the Quadratic Equation in JavaScript provides a solid base for learning more complex algorithms and enhancing problem-solving skills. To explore more programming lessons, visit Newtum for insightful tutorials. Start coding your way to proficiency today!

          Edited and Compiled by

          This blog was compiled and edited by Rasika Deshpande, who has over 4 years of experience in content creation. She’s passionate about helping beginners understand technical topics in a more interactive way.

          About The Author