calculate sum of all numbers
in an array
[ forEach ]

Calculate sum of all numbers

Write a function that takes an array of numbers and returns the sum of all the numbers in that array.


Example ...

Enter an array ...

[1, 2, 3, 4, 5, 6] array

21 sum of all numbers in the array

1 + 2 + 3 + 4 + 5 + 6 = 21

Arrays are used to store multiple values in a single variable.

Each value is called an element, and each element has a numeric position in the array, known as its index.

Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Arrays can contain any data type, including numbers, strings, and objects.

const arr1 = [2, 4, 6]; array

arr1[0]; element at index 0 → 2

arr1[1]; element at index 1 → 4

arr1[2]; element at index 2 → 6

arr1[3]; element at index 3 → undefined index not found


Numbers are used to represent both integer and floating-point values.

Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴

let num1 = 5; → number

let num2 = 2.5; → number

let num3 = num1 + num2;

console.log(num3); returns ↴

7.5 → number


Calculate sum of all numbers using the forEach() method ↴


forEach() method calls a function for each element in an array, executing a provided function once for each array element.

The method does not return a new array, it always returns undefined

const arr2 = [2, 4, 6, 8];

arr2.forEach((element, index, array) => {

array[index] = element * 2;

});

console.log(arr2); returns ↴

[4, 8, 12, 16] → value of each element is doubled

const arr3 = [2, 4, 6, 8];

arr3.forEach((element, index) => {

console.log(index, element)

}); returns ↴

0 2

1 4

2 6

3 8 → index and element printed to console

Use forEach() when an action is needed to be performed on each element,

not when a new array needs to be generated from the current one.


Initialize a variable to hold the array to calculate the sum of all numbers.

const array1 = [2, 4, 6, 8, 10]; → user input


Define a function findSum to calculate the sum of all numbers in an array.

function findSum(arr) {}

The function takes an array as input arr and returns the sum of all numbers in that array.

Initialize sum variable to store the total.

let sum = 0 sum

forEach() method loops through the array, executing a callback function once for each array element.

arr.forEach(callbackFn)

callback function ↴

(num) => sum += num

num → current element being processed in the array

Add the current number num to sum

Return the total sum.

return sum


Call the function with ↴

findSum(array1);


Calculate sum of all numbers in an array.

const array1 = [2, 4, 6, 8, 10];

function findSum(arr) {

let sum = 0;

arr.forEach((num) => {

sum += num;

});

return sum;

}

call function

findSum(array1); returns ↴

30

Calculate sum of all numbers in an array