How to Add Numbers in Javascript – A Beginner’s Guide

INTRODUCTION

NOT REALLY THAT EASY?

Welcome to a beginner’s tutorial on how to add numbers in Javascript. How difficult can it be to add two numbers together? Well, to add 2 numbers in Javascript, simply 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);

It should be a piece of cake now, right? Well, not really. Beginners usually run into a couple of problems – How to add numbers from textboxes, prompt boxes, and why numbers get concatenated together instead. So here it is, this guide will walk through some examples. 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.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

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

 

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.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer 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.

 

SECTION A

ADD NUMBERS IN TEXTBOXES

All right, let us now start with the simple and classic “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"/>
  <br>
  VAR Y = <input type="number" id="varY" required value="5"/>
  <br>
  VAR RESULT = <input type="number" id="varResult" readonly/>
  <br>
  <input type="submit" value="Add Them!"/>
</form>

The HTML part is super straightforward. This is just a simple HTML <form> with 3 number fields – Two for number input, and the third one 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, a super easy 3-steps:

  • Get the input values from the text boxes.
  • Add the numbers together.
  • Output the result.

But here comes the common newbie mistake – When we adapt 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
}

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 =

 

SECTION B

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

 

 

EXTRA

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/PropertyDescriptionReference Link
getElementById("ID")Get the HTML element with the given ID.Click Here
typeof VARIABLEReturns the data type of the given variable.Click Here
ELEMENT.valueGet 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)

 

CLOSING

WHAT’S NEXT?

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. Required fields are marked *