How to find the sum of array elements in JavaScript?
Hello everyone! I just started learning JavaScript and ran into a problem. I have an array of numbers, for example:
```javascript
let numbers = [10, 20, 30, 40, 50];
```
I need to get the sum of all elements of this array, that is, the result: 150. I tried to do it manually using a loop, but my code doesn't work:
```javascript
let sum = 0;
for (let i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // Outputs NaN
```
I understand that something is wrong with the loop condition, but I can't figure it out. I also heard that JavaScript has some built-in methods for working with arrays, for example, `reduce()`. But I don't know how to use them correctly. Please tell me how to correctly find the sum of array elements? Preferably with examples and explanations for beginners.
No answers yet.
Log in to leave an answer
Blogs