OneBite.Dev - Coding blog in a bite size

add numbers in an array javascript

Code snippet for how to how to add numbers in an array javascript with sample and detail explanation

In the world of programming, arrays are a vital building block for structuring and organizing data. In JavaScript, arrays provide diverse ways to manipulate and interact with data. This simple guide will walk you through how to add numbers in an array using JavaScript.

Code snippet: Adding Numbers in an Array

Let’s look at a simple script to add numbers in an array.

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

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

console.log(sum);

Code Explanation for Adding Numbers in an Array

The first line of code declares an array named ‘numbers’. In this scenario, it’s filled with five integers.

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

The next line declares a variable named ‘sum’, which is initially set to zero. It will eventually store the total sum of all numbers in the array.

let sum = 0;

Next, a ‘for’ loop is set up to iterate over each item in the array. The ‘i’ variable is initialized at zero because array items are indexed starting from zero in JavaScript.

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

Within the loop, each number in the array is added to the ‘sum’ variable. This is achieved with the ’+=’ operator, which is shorthand for ‘sum = sum + numbers[i];‘.

    sum += numbers[i]; 
}

Finally, the sum of the numbers is printed to the console with ‘console.log(sum);‘.

This approach is simple and straightforward. It demonstrates the basic concept of looping through an array, performing an operation on each element, and storing the result. With this understanding, you should be able to apply the concept to more complex calculations and operations involving arrays in JavaScript.

javascript