Modified version of summing an array with recursion in JavaScript

Let’s say, we are required to write a recursive function that sums all the elements of an array of Numbers but with a twist and the twist is that the recursive function we write cannot initialize any extra variable (memory).

Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all has to be using what we already have.

Here’s the solution −

We already have an array and can use its first element (i.e., the element at zeroth index to hold the recursive sum).

The approach is that we repeatedly pop one element from the array and add it to the first element of the array until we are left with only one element.

When we are left with only one element, it will be the cumulative sum of the array and we return that. The code for this approach will be −


const recursiveSum = arr => {
   if(arr.length > 1){
      arr[0] += arr.pop();
      return recursiveSum(arr);
   return arr[0];


The output in the console will be −