Add Two Numbers in Javascript (Simple 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, it’s not really straightforward.

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.

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/how-to-add-two-numbers-in-javascript/” title=”How to Add Two Numbers in Javascript” poster=”https://code-boxx.com/wp-content/uploads/2023/02/STORY-JS-R4.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

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 JAVASCRIPT

All right, let us now get into the simple examples of how to add numbers in Javascript.

 

EXAMPLE 1) ADD NUMBERS IN TEXT BOXES

1A) 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 show the result.

 

1B) JAVASCRIPT – WRONG WAY TO ADD NUMBERS

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
}
VAR X =
VAR Y =
VAR RESULT =

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 go ahead and see the result for yourself – 3 + 5 = 35. Just what is going on? Here comes the common newbie mistake – When we get the value from a text box, it is of the string data type. When we “add” strings together, they will concatenate instead.

 

 

1C) JAVASCRIPT – RIGHT WAY TO ADD NUMBERS

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
}
VAR X =
VAR Y =
VAR RESULT =

To “fix” the above “error”, it is as simple as parsing the value as an integer before adding them – That’s all.

 

 

EXAMPLE 2) ADD NUMBERS USING PROMPT

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.

 

 

EXTRA BITS & 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

 

PARSE NUMBER SHORTHAND

I love to reward people who take the time to read. Instead of using parseInt(document.getElementById("ID").value), we can use a shorthand – +document.getElementById("ID").value.

 

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!

1 thought on “Add Two Numbers in Javascript (Simple Examples)”

Leave a Comment

Your email address will not be published. Required fields are marked *