How Can I Calculate The Sum Of A Given Array Of Numbers Using JavaScript?

To find the sum of an array of numbers in JavaScript, you can use a loop to iterate over each element and add it to a running total. Here’s an example:

const numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];

console.log(sum); // Output: 15

Alternatively, you can use the reduce method which applies a function to each element of the array in order to reduce it to a single value:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // Output: 15

In the above code, reduce starts with an initial value of 0 and adds each element of the array (currentValue) to the accumulator. The final sum is returned as the result.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!