JavaScript Program to Add Two Numbers on Button click

Are you new to JavaScript or recently been asked how to add a JavaScript function to an HTML? Check this post to learn how to write and call a JavaScript method in html document.

In this article, we will see how to add two numbers in JavaScript in the following 2 ways.

  • Add two given numbers in plain JavaScript
  • Add two numbers using input fields

We will see both ways with examples below.

Add two given numbers in plain JavaScript

The addition of 2 numbers in JavaScript happens the same way as in any other language. Initialize 2 variables with some values and add them using the + operator.

See the example below

<script>
    function add(num1, num2) {
      return num1 + num2
    }

    const num1 = 12
    const num2 = 23
    console.log(add(num1, num2))
</script>

Output

35

document.write() is used to write directly to an HTML document.

Add two numbers using input fields

In this example, we will create input fields where a user can enter the numbers. Then, we will have a button which when clicked will add the entered numbers and print it.

We will create a JavaScript function that will do this addition.

See the example below

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Add two numbers in plain JavaScript</title>
  <script>
    function add() {
      let first = parseInt(document.getElementById("first").value)
      let second = parseInt(document.getElementById("second").value)
      document.getElementById("sum").innerHTML = first + second
    }
  </script>
</head>
<body>
<table>
  <tr>
    <td><label for="first">first number </label></td>
    <td><input type="number" id="first"/></td>
  </tr>
  <tr>
    <td><label for="second">second number </label></td>
    <td><input type="number" id="second"/></td>
  </tr>
  <tr>
    <td>
      <button onclick="add()">Add</button>
    </td>
    <td><span id="sum"></span></td>
    //output to be here
  </tr>
</table>
</body>
</html>

Output

parseInt() function is used to parse any string to a number.