Как посчитать сумму элементов массива?
Надо написать функцию, которая принимает массив чисел и возвращает их сумму.
Вот мой неудачный код:
- Вопрос задан более двух лет назад
- 22421 просмотр
- Вконтакте

Странно, столько ответов и ни одного редьюса.
А ещё почему-то никого не смутило, что автор к константе присваивает новое значение.
Как сложить все элементы массива js

Можно использовать обычный цикл, но есть более красивое решение. Метод reduce() , принимает в качестве аргумента массив и колбек функцию, которая применяется к каждому элементу массива и таким образом позволяет найти их сумму. Вот пример:

Немного улучшу reduce .
А за такое использование map могут и побить. Если уж и хочется из цикла что-то менять снаружи (что почти всегда плохая идея), то для этого используют forEach . Map возвращает значение, которое должно быть использовано. И map не должен менять ничего извне. Иначе код становится сложноподдерживаемым.
JavaScript: 6 Ways to Calculate the Sum of an Array
This practical, succinct article walks you through three examples that use three different approaches to find the sum of all elements of a given array in Javascript (suppose this array only contains numbers). Without any further ado, let’s get started.
Using Array.reduce() method
If you’re using modern Javascript (ES6 and beyond), this might be the neatest and quickest solution.
Example:
Output:
The reduce() method executes a reducer function for elements of an array. It returns the accumulated result from the last call of the callback function. Below is the syntax:
Where:
- total (required): The initial value, or the previously returned value of the function
- current (required): The current element
- current (optional): The index of the current element
- arr (optional): The array that the current element belongs to
Javascript is interesting, and it also has another method quite similar to the reduce() method, named reduceRight() . You can get the sum of a numeric array with only a single line of code like this:
Output:
Using a classic For loop
This is an easy-to-understand approach and has been used for decades. However, the code is a bit longer.
Example:
Output:
Using modern For/Of loop
This approach also uses a loop but is more concise than the previous one. Like the Array.reduce() method, for/of was added to ES6 (JS 2015).
Example:
Output:
Using the map() method
The Array.map() method is new in ES6 and beyond. This one is very useful when you have to deal with an array, including finding the sum of its elements.
Example:
Output:
Using a While loop
Another way to sum the elements of an array for your reference (basically, it’s quite similar to other methods of using loops).
Example:
Output:
Using a forEach loop
Just another kind of loop in Javascript. Here’s how to make use of it to calculate the total value of a given array:
Output:
Conclusion
We’ve walked through several ways to get the sum of all elements of a given array in Javascript. Although just one method is enough, knowing the existence of other methods also helps you a lot in mastering the art of programming. Good luck and happy coding!
How to get the sum of an array in JavaScript
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
In this shot, we will discuss three methods you can use to get the total of a given array in JavaScript.
First, we’ll use the traditional for loop. Secondly, we’ll use forEach , an array-like method, and lastly, we’ll make use of for. of .
In this shot, our array example is [1, 4, 0, 9, -3] , and the expected output is 11 .
1. Using the traditional for loop
In this method, you iterate and add each item until you reach the last item.