Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does same javascript code give different result?

I am a beginner at javascript. I find following piece of code a bit difficult for me. I think both are same, and should have give the same result. But they are throwing different result.

var a = 5,
  b = 6,
  c = 7;

if (a + b > c || b + c > a || a + c > b) {
  let s = (a + b + c) / 2;
  let area = Math.sqrt(s * ((s - a) * (s - b) * (s - c)));
  console.log(`The area of the triangle is: ${area}`);
} else {
  console.log('Triangle does not exist');
}

It gives me a result. But when i try to take input from user and input the same value (5,6,7), find different result.

var a = prompt(),
  b = prompt(),
  c = prompt();

if (a + b > c || b + c > a || a + c > b) {
  let s = (a + b + c) / 2;
  let area = Math.sqrt(s * ((s - a) * (s - b) * (s - c)));
  console.log(`The area of the triangle is: ${area}`);
} else {
  console.log('Triangle does not exist');
}

Maybe I am wrong. But I just want know the reason.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

My assumption is that this is related to prompt() returning a string and not an integer. Therefore the additions of the variables a, b and c would concatenate the strings and only after that – caused by the comparison > and after division / – convert it to a number. So in order to fix this, I think using parseInt() to parse the numbers returned from prompt() would fix the issue

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading