find the sum of all elements in an array in javascript

Here's one way to find the sum of all elements in an array using a for loop and the addition operator:

index.tsx
let nums = [1, 2, 3, 4, 5];
let sum = 0;

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

console.log(sum); // Output: 15
135 chars
9 lines

We start by declaring an array nums with some values. Then we declare a variable sum and initialize it to 0.

Next, we loop through the array using a for loop. For each iteration of the loop, we add the current element to the sum variable using the addition operator.

Finally, we print the sum to the console using the console.log() statement.

gistlibby LogSnag