How to Add Two Numbers in Javascript (Quick Examples)

Welcome to a tutorial on how to add two numbers in Javascript. Adding two numbers together should be a piece of cake now, right? Well, not really.

To add 2 numbers in Javascript, get the values from the fields and parse them into integers before adding:

  • var first = document.getElementById("FIRST").value;
  • var second = document.getElementById("SECOND").value;
  • var added = parseInt(first) + parseInt(second);

That covers the basics, but let us walk through a few more examples in this guide. Read on!

ⓘ I have included a zip file with all the example code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Textbox Add Prompt Add
Summary & Links The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

ADD NUMBERS IN TEXTBOXES

All right, let us now start with the simple and classic example of “how to get the values from HTML text boxes and add them together”.

 

THE HTML

1a-textbox-add.html
<form onsubmit="return add();">
  VAR X = <input type="number" id="varX" required value="3"/>
  VAR Y = <input type="number" id="varY" required value="5"/>
  VAR RESULT = <input type="number" id="varResult" readonly/>
  <input type="submit" value="Add Them!"/>
</form>

The HTML part is straightforward, this is just an HTML <form> with 3 number fields:

  • varX and varY are the two number input fields.
  • varResult to output the result into.

 

JAVASCRIPT – THE WRONG WAY

1b-textbox-add-wrong.js
function add () {
  // (A) GET THE VALUE FROM THE TEXT BOXES
  var x = document.getElementById("varX").value;
  var y = document.getElementById("varY").value;

  // (B) ADDITION - THE WRONG WAY
  // IMPORTANT NOTE: X AND Y ARE STRINGS
  // WHEN WE "ADD" THEM, THEY CONCATENATE INSTEAD
  console.log(typeof x); // string
  console.log(typeof y); // string
  var result = x + y;

  // (C) OUTPUT RESULT
  document.getElementById("varResult").value = result;
  return false; // Stop form submit
}

Yep, that’s all to the Javascript.

  1. Get the input values from the text boxes.
  2. Add the numbers together.
  3. Output the result.

But here comes the common newbie mistake – When we get the value from a text box, it is of the string data type. Remember that when we “add” strings together, they concatenate instead? See it in action in the negative demo below.

 

 

THE NEGATIVE DEMONSTRATION

VAR X =
VAR Y =
VAR RESULT =

 

JAVASCRIPT – THE RIGHT WAY

1c-textbox-add-right.js
function add () {
  // (A) GET THE VALUE FROM THE TEXT BOXES
  // NOTE - WE PARSE THEM AS INTEGER
  var x = parseInt(document.getElementById("varX").value);
  var y = parseInt(document.getElementById("varY").value);

  // (B) ADDITION
  // NOW THEY ADD PROPLERLY, NOT CONCATENATE
  console.log(typeof x); // number
  console.log(typeof y); // number
  var result = x + y;

  // (C) OUPUT RESULT
  document.getElementById("varResult").value = result;
  return false; // Stop form submit
}

Yes, the above negative demonstration will end up with a result of "3" + "5" = "35". So the “quick fix” here is as simple as parsing the value as an integer before adding them – That’s all.

 

THE CORRECT DEMO

VAR X =
VAR Y =
VAR RESULT =

 

 

ADD NUMBERS USING PROMPT

Now that you know the secrets behind how to add two numbers, we can simply do the same with a prompt.

 

HTML & JAVASCRIPT

2-prompt-add.html
<script>
function add () {
  // (A) THE PROMPTS
  var x = prompt("Please enter the first nunmber", "5");
  var y = prompt("Please enter the second nunmber", "3");

  // (B) CHECK AND PARSE STRING TO INTEGER
  if (isNaN(x) || isNaN(y)) {
    alert("Invalid Input");
  } else {
    x = parseInt(x);
    y = parseInt(y);
    console.log(typeof x); // number
    console.log(typeof y); // number

    // (C) THE RESULT
    var result = x + y;
    alert(result);
  }
}
</script>
<input type="button" value="Add Numbers!" onclick="add()"/>

Yep, this shouldn’t need more explanation. You expert code ninjas should already know what this does by now. But one tiny bit of advice here – We cannot set the prompt() function to have multiple fields at once, nor can we restrict the input to numbers… So stick with using HTML <form> and <input> where possible.

 

THE RESULT

 

 

SUMMARY & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

Function/Property Description Reference Link
getElementById("ID") Get the HTML element with the given ID. Click Here
typeof VARIABLE Returns the data type of the given variable. Click Here
ELEMENT.value Get or set the value property of the given HTML element. Click Here
parseInt(VALUE) Parse the given value into an integer (whole number). Click Here
parseFloat(VALUE) Parse the given value into a decimal number. Click Here
isNaN(VALUE) Checks if the given value is not a number. Click Here

 

THE CHEATSHEET

How To Add Numbers In Javascript (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand the basic mechanics of Javascript, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.