Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript (+) sign concatenates instead of giving sum?

I created a simple program that make the sum of two numbers BUT.. the program is concatenating instead, This is so confusing! Can anyone help?

function calculate() {
  var numberOne = document.querySelector(".first").value;
  var numberTwo = document.querySelector(".second").value;
  var sum = numberOne + numberTwo;
  document.querySelector(".result").innerHTML = "The sum of the two numbers is : " + sum;
}
<!doctype html>
<html>

<body>
  <p>Calculate sum of two numbers !</p>
  Enter 1rst Number:<br>
  <input type="number" class="first" placeholder=""><br><br> Enter 2nd Number:<br>
  <input type="number" class="second" placeholder=""><br><br>
  <input type="button" onclick="calculate()" value="calculate">
  <p class="result"></p>
</body>

</html>
like image 282
Elight7 Avatar asked Aug 23 '17 13:08

Elight7


People also ask

Why is my JavaScript concatenating instead of adding?

The reason that adding 2 numbers together in JavaScript is that one or more of the operands that we try to add together may not be numbers. Therefore, we should make sure that they're both numbers before trying to add them. To do this, we can convert to numbers with various functions or operators.

Is concatenating instead of adding?

JavaScript (+) sign concatenates instead of giving sum? The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.

How do I stop concatenation?

To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.

How do you sum a number in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.


1 Answers

Here value gives you a string, hence the concatenation. Try parsing it as an Number instead:

var sum = parseInt(numberOne) + parseInt(numberTwo);

See the demo fiddle.

like image 181
Suresh Atta Avatar answered Oct 07 '22 17:10

Suresh Atta