What is an array in JavaScript?
An array in JavaScript is a collection of data that is designed to store multiple values in a single variable. A JavaScript array is created using square brackets "[...]" and enumerating the array elements using commas or by using the "new Array()" constructor. Each value in the array has its serial number (index), which allows you to access the element by index. In JavaScript, arrays start at index zero. JavaScript provides a rich set of built-in functions for joining, slicing, reversing, merging, copying, containing, cloning, inserting, clearing, and reducing arrays. You can also convert string to array, convert array to JSON, convert array to string, and get a sum of array elements.
How to find the sum of array elements in JavaScript?
To find the sum of array elements in JavaScript, you can use the array.reduce(function(total, currentValue, currentIndex, array), initialValue) method. The callback function will not be called on removed or missing array elements. The array.reduce() method does not change the array it was called on. The range of elements processed by the reduce() method is set before the first call to the callback function. If new elements have been added to the array since the reduce() method was called, then the callback function will not be called for those elements.
The return value of the callback function is provided as an argument for the following callback function call, causing the last call's return value to become the method's return value.
JavaScript Sum Array Examples
The following are examples of getting the sum of array elements in JavaScript:
Getting the sum of array elements
The following is an example of getting the sum of the elements of a JavaScript array using the array.reduce() method and an initial value:
Getting the sum of array elements using a forEach loop
The following is an example of getting the sum of the elements of a JavaScript array using a forEach loop:
Getting the sum of array elements using the map() method
The array.map() method is new in ES6. The following is an example of getting the sum of the elements of a JavaScript array using the map() method:
Getting the sum of array elements using a for loop
In JavaScript, the for loop is used to iterate over an iterable object. We can use a for loop to loop through the array elements and sum their values. The following is an example of getting the sum of the elements of a JavaScript array using a for loop:
Getting the sum of array elements using a for/of loop
The following is an example of getting the sum of the elements of a JavaScript array using a for/of loop:
Getting the sum of array elements using a while loop
The following is an example of getting the sum of the elements of a JavaScript array using a while loop: