- Sum function in javascript
- # Table of Contents
- # Get the Sum of an Array of Numbers in JavaScript
- # Creating a reusable function
- # Get the Sum of an Array of Numbers using a for. of loop
- # Get the Sum of an Array of Numbers using Array.forEach()
- # Get the Sum of an Array of Numbers using a for loop
- # Get the Sum of an Array of Numbers using a while loop
- # Get the Sum of an Array of Numbers using lodash
- # Additional Resources
- Function sum #
- Syntax #
- Parameters #
- Returns #
- Throws #
- Examples #
- Javascript Sum Values
- 8 Answers 8
- JavaScript: 6 Ways to Calculate the Sum of an Array
- Using Array.reduce() method
- Using a classic For loop
- Using modern For/Of loop
- Using the map() method
- Using a While loop
- Using a forEach loop
- Conclusion
Sum function in javascript
Last updated: Dec 26, 2022
Reading time · 5 min
# Table of Contents
# Get the Sum of an Array of Numbers in JavaScript
To get the sum of an array of numbers:
- Use the Array.reduce() method to iterate over the array.
- Set the initial value in the reduce method to 0 .
- On each iteration, return the sum of the accumulated value and the current number.
Copied!const arr = [5, 15, 45]; const sum = arr.reduce((accumulator, value) => return accumulator + value; >, 0); console.log(sum); // 👉️ 65
The function we passed to the Array.reduce method gets called for each element in the array.
We initialized the accumulator variable to 0 because that’s what we passed as the second argument to the reduce() method.
After the last iteration, the sum variable stores the sum of the numbers in the array.
# Creating a reusable function
If you have to calculate the sum of arrays often, define a reusable function.
Copied!function calculateSum(array) return array.reduce((accumulator, value) => return accumulator + value; >, 0); > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter and calculates the sum of the numbers in the array.
You can also shorten the function we passed to the reduce() method by using an implicit return statement.
Copied!function calculateSum(array) return array.reduce((accumulator, value) => accumulator + value, 0); > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The arrow function in the example uses an implicit return.
An alternative and perhaps simpler approach is to use a for. of loop.
# Get the Sum of an Array of Numbers using a for. of loop
This is a three-step process:
- Declare a sum variable and initialize it to 0 .
- Use the for. of loop to iterate over the array.
- On each iteration, reassign the sum variable to its current value plus the value of the current element.
Copied!const arr = [5, 15, 45]; let sum = 0; for (const value of arr) sum += value; > console.log(sum); // 👉️ 65
If you need to handle non-numeric values, use the typeof operator.
Copied!// 👇️ array contains non-numeric values const arr = ['a', 5, 'b', 15, 'c', 45]; let sum = 0; for (const value of arr) if (typeof value === 'number') sum += value; > > console.log(sum); // 👉️ 65
The array in the code sample also contains non-numeric values, so we used the typeof operator to check if each value is a number before adding it to the total.
The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .
Notice that we declared the sum variable using the let keyword. Had we declared the variable using const , we wouldn’t be able to reassign it.
On each iteration, we reassign the sum variable to its current value plus the value of the current element.
If you have to do this often, extract the logic into a reusable function.
Copied!function calculateSum(array) let total = 0; for (const value of array) total += value; > return total; > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter, calculates the sum of its values and returns the result.
Alternatively, you can use Array.forEach() .
# Get the Sum of an Array of Numbers using Array.forEach()
This is a three-step process:
- Declare a new sum variable and initialize it to 0 .
- Use the Array.forEach() method to iterate over the array.
- On each iteration, reassign the value of the sum variable to its current value plus the array element.
Copied!const arr = [5, 15, 45]; let sum = 0; arr.forEach(value => sum += value; >); console.log(sum); // 👉️ 65
The function we passed to the Array.forEach method gets called with each element in the array.
On each iteration, we reassign the value of the sum variable to its current value plus the value of the current array element.
The sum variable stores the sum of the values in the array after the last iteration.
If you have to calculate the sum of an array’s elements often, define a reusable function.
Copied!function calculateSum(array) let total = 0; array.forEach(value => total += value; >); return total; > const result1 = calculateSum([1, 2, 3]); console.log(result1); // 👉️ 6 const result2 = calculateSum([1, 2, 3, 4]); console.log(result2); // 👉️ 10
The calculateSum() function takes an array as a parameter, calculates the sum of the array’s elements and returns the result.
Alternatively, you can use a basic for loop.
# Get the Sum of an Array of Numbers using a for loop
This is a three-step process:
- Declare a new sum variable and initialize it to 0 .
- Use a for loop to iterate over the array.
- Reassign the value of the sum variable to its current value plus the current array element.
Copied!const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index arr.length; index++) sum += arr[index]; > console.log(sum); // 👉️ 65
We used a basic for loop to iterate over the array.
On each iteration, we use the index to access the current array element and reassign the sum variable.
Which approach you pick is a matter of personal preference. I’d use the Array.reduce() method or a for. of loop as both options are quite direct and intuitive.
# Get the Sum of an Array of Numbers using a while loop
You can also use a while loop to get the sum of an array of numbers.
Copied!const arr = [5, 15, 45]; let sum = 0; let i = -1; while (++i arr.length) sum += arr[i]; > console.log(sum); // 👉️ 65
We initialized the sum and i variables using the let keyword.
Using let is important because variables declared using const cannot be reassigned.
On each iteration of the while loop, we increment the i variable and add the current array element to the total.
# Get the Sum of an Array of Numbers using lodash
If you use the lodash library, you can also use the lodash.sum() method to get the sum of an array of numbers.
Copied!import _ from 'lodash'; console.log(_.sum([1, 2, 3])); // 👉️ 6 console.log(_.sum([10, 20, 30])); // 👉️ 60
If you need to install lodash , run the following command.
Copied!# 👇️ initialize a package.json file if you don't have one npm init -y npm install lodash
The lodash.sum method takes an array as a parameter and computes the sum of the values in the array.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Function sum #
Compute the sum of a matrix or a list with values. In case of a multidimensional array or matrix, the sum of all elements will be calculated.
Syntax #
math.sum(a, b, c, . ) math.sum(A) math.sum(A, dimension)
Parameters #
Returns #
Throws #
Examples #
math.sum(2, 1, 4, 3) // returns 10 math.sum([2, 1, 4, 3]) // returns 10 math.sum([[2, 5], [4, 3], [1, 7]]) // returns 22
Javascript Sum Values
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
Perhaps a duplicate since the code given does not produce the error: stackoverflow.com/q/14496531/4294399
8 Answers 8
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you’re not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
yeah. i don’t use any quotes for the values. i also already converted them to int by using parseInt(a) and parseInt(b). am i doing it right ?
well it depends. parseInt(a) doesn’t change the a variable, it returns the parsed int. So you might need to a = parseInt(a) or c = parseInt(a) + parseInt(b)
I can see that specifying the radix would help for readability, but is it really necessary here? It’s probably a more than valid assumption that this app is going to be summing base 10 numbers. Edit: I guess given that he is parsing numbers there’s the chance a ‘0’ could be prepended or something. I concede the point 😛
Better to convert to number using, well ehr, Number . No need for radix — so Number(’08’) returns 8, not 0.
The author has probably put «simplified» code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using «Number()» solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
var a = 2; var b = 5; var c = a + b; // c is now 7
The code you show will not work the way you describe. It will result in 7 .
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter ( radix ) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt() .)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].
JavaScript: 6 Ways to Calculate the Sum of an Array
This practical, succinct article walks you through three examples that use three different approaches to find the sum of all elements of a given array in Javascript (suppose this array only contains numbers). Without any further ado, let’s get started.
Using Array.reduce() method
If you’re using modern Javascript (ES6 and beyond), this might be the neatest and quickest solution.
// define a reusable function const calculateSum = (arr) => < return arr.reduce((total, current) =>< return total + current; >, 0); > // try it console.log(calculateSum([1, 2, 3, 4, 5]));
The reduce() method executes a reducer function for elements of an array. It returns the accumulated result from the last call of the callback function. Below is the syntax:
array.reduce(function(total, current, index, arr), initialValue)
- total (required): The initial value, or the previously returned value of the function
- current (required): The current element
- current (optional): The index of the current element
- arr (optional): The array that the current element belongs to
Javascript is interesting, and it also has another method quite similar to the reduce() method, named reduceRight() . You can get the sum of a numeric array with only a single line of code like this:
const sum = [1, 2, 3, 4, 5].reduceRight((acc, cur) => acc + cur, 0); console.log(sum);
Using a classic For loop
This is an easy-to-understand approach and has been used for decades. However, the code is a bit longer.
// define a reusable function function calculateSum(arr) < var sum = 0; for (var i = 0; i < arr.length; i++) < sum += arr[i]; >return sum; > // try it console.log(calculateSum([1, 2, 3, 4]));
Using modern For/Of loop
This approach also uses a loop but is more concise than the previous one. Like the Array.reduce() method, for/of was added to ES6 (JS 2015).
const arr = [9, 8, 7, 6, 5]; let sum = 0; for (let e of arr) < sum += e; >console.log(sum);
Using the map() method
The Array.map() method is new in ES6 and beyond. This one is very useful when you have to deal with an array, including finding the sum of its elements.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; let sum = 0 arr.map(e => sum += e) console.log(sum);
Using a While loop
Another way to sum the elements of an array for your reference (basically, it’s quite similar to other methods of using loops).
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let sum = 0; let i = -1; while (++i < arr.length) < sum += arr[i]; >console.log(sum);
Using a forEach loop
Just another kind of loop in Javascript. Here’s how to make use of it to calculate the total value of a given array:
const array = [1, 2, 3, 4]; let sum = 0; array.forEach(e => < result += e; >) console.log(result);
Conclusion
We’ve walked through several ways to get the sum of all elements of a given array in Javascript. Although just one method is enough, knowing the existence of other methods also helps you a lot in mastering the art of programming. Good luck and happy coding!