Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
JavaScript Quadratic Formula Equation producing NaN

I am making a quadratic formula calculator. There are no errors but when I run it it returns NaN. I do not understand why.

function quadratic(a, b, c) {    
  a = document.getElementById("a").value;
  b = document.getElementById("b").value;
  c = document.getElementById("c").value;

  var equation = Math.sqrt((b * b) - ( 4 * a * c));
  var quadraticPos =(-b + equation) / (2 * a); 
  var quadraticNeg = (-b - equation) / (2 * a);

  if (isNaN(a) || isNaN(b) || isNaN(c)) {
    alert("Invalid Input");
  } else {
    document.getElementById("quadraticOut").innerHTML =
      "Quadratic Equation = " + quadraticPos.toFixed(2) +
      "<br/>" + quadraticNeg.toFixed(2);
  }
}
input { width: 20px }
<input id="a" placeholder="a"/>
<input id="b" placeholder="b"/>
<input id="c" placeholder="c"/>
<button onclick="quadratic()">compute</button>
<div id="quadraticOut">result…</div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. The input check should come before the actual calculation.

  2. a, b and c are by default strings, not numbers, when they come from the input fields through .value. They should be converted to Number() before being used in calculation. Or, you could multiply by a number, but that's a hack. If b*b multiplies two strings, the product will be a number because of type coercion, but this isn't solid and you should not rely on JavaScript oddities like this to make your calculation work.

  3. Math.sqrt() returns NaN if the result is a negative number, which is very likely to get with random input values here.

  4. Your <br/>in the innerHTML will cause an error, you need to put quotes around it.

  5. In 2021 it would be better to use let and/or const in order to limit the variable scope, instead of the global var.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!