Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

When I add two numbers, I’m not getting the expected output. For example, 1 + 2 returns 12 and not 3. 

Below is my code implementation: 

function myFunction() {

  var y = document.getElementById("txt1").value;

  var z = document.getElementById("txt2").value;

  var x = y + z;

  document.getElementById("demo").innerHTML = x;

}

<p>

  Click the button to calculate x.

  <button onclick="myFunction()">Try it</button>

</p>

<p>

  Enter first number:

  <input type="text" id="txt1" name="text1" value="1">

  Enter second number:

  <input type="text" id="txt2" name="text2" value="2">

</p>

<p id="demo"></p>

Can anyone tell me why instead of calculating the sum it’s concatenating the numbers? 

1 Answer

0 votes
by (19.7k points)

You are giving a string, to produce a number prepend the string with + like below: 

var x = +y + +z;

Interested in Java? Check out this Java Certification by Intellipaat.   

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...