This callback function takes two arguments: If you didn't provide an initial value, JavaScript uses the first element of the array as the initial value and starts iterating from the second element.įor each element in the array, Array.reduce() calls the callback function that you passed as an argument.
When you call Array.reduce() on an array, JavaScript starts by setting the initial value of the accumulator to the initial value you provided (if any).
Now let's take a closer look at how the Array.reduce() function works behind the scenes. In this example, we start with an array of numbers and use the Array.reduce() function to find the sum of all the elements in the array. Enter fullscreen mode Exit fullscreen mode