The array of numbers can be integers or floats, and we can use several methods to calculate the sum.
Whether you are a beginner or an experienced programmer, this tutorial will help you understand the basics of summing up an array of numbers in JavaScript.
In this Javascript tutorial, we will learn how to find the sum of an array of numbers in JavaScript.
Array.reduce() Method
The Array.reduce() method is one of the most popular and efficient ways of finding the sum of an array of numbers in JavaScript.
This method iterates through each element of the array and accumulates a value based on the logic provided in the callback function.
Here is an example code:
const numbers = [10, 20, 30, 40, 50]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // Output: 150
In this code, we have created an array numbers
containing 5 numbers.
The Array.reduce()
method takes two arguments, the accumulator and the current value.
The accumulator starts with the initial value of 0 and adds up each element of the array as it iterates through it.
Finally, the sum of all elements is stored in the sum
variable, which is 150.
For Loop
Another way to find the sum of an array of numbers in JavaScript is to use a for loop.
This method is straightforward and easy to understand, even for beginners.
Here is an example code:
const numbers = [10, 20, 30, 40, 50]; let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum); // Output: 150
In this code, we have created an array numbers
containing 5 numbers.
The sum
variable is initialized with 0, and we use a for loop to iterate through each element of the array.
We add up each element to the sum
variable, and finally, the sum of all elements is stored in the sum
variable, which is 150.
Conclusion
In this tutorial, we have learned how to find the sum of an array of numbers in JavaScript using two methods: the Array.reduce() method and the for loop method.
Both methods are efficient and easy to understand, and you can choose the one that suits your needs and skill level.
I hope you found this tutorial helpful. If you have any questions or feedback, feel free to leave a comment below.