How to Find the Sum of Numbers in an Array in Javascript
In this tutorial, you will learn how to find the sum of numbers in an array in javascript. As you already know, an array is nothing more than a collection of items and the data type of these items can be the same or different.
If you are a beginner, then getting some of the individual numbers is easy by simply using the addition operator (+
), but when these numbers are in an array, things can be a bit tricky.
There are multiple ways to get the sum of numbers in an array, but I found reduce()
method to be the perfect fit in this situation and this is something that we are going to use to accomplish our goal.
In the following example, we have an array of numbers. Upon click of a button, we will get the sum of all the numbers and display that on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 3 elements in the HTML file (
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements. - The
button
element has“Get”
and theh1
element has“Result”
asinnerText
. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Get</button> <h1>Result</h1> </div> <script src="script.js"></script> </body> </html>
body { text-align: center; } div { display: inline-block; } button { display: inline-block; padding: 10px 20px; }
Javascript
- We have selected the
button
element and theh1
element using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We have global variable
numbers
which holds an array of numbers. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are calling
reduce()
method and providing 0 as the second parameter to act as our default accumulated value to start with. If you do not provide it, then reduce method will pick the first element from the array. In case, your array is empty and there is no default accumulated value, then you will get an error. That’s why it is important to provide some default accumulated value to start with. - Finally, the
reduce()
method returns the sum of numbers in the array and we are displaying that in theh1
element using theinnerText
property.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); let numbers = [ 10, 20, 30, 40]; btnGet.addEventListener('click', () => { result.innerText = numbers.reduce((total, current) => total + current, 0); });