Home > Software engineering >  Recursion in Js
Recursion in Js

Time:10-04

Can someone please explain to me why we need (n-1) in the following code.

  function multiply(arr, n) {
    if (n <= 0) {    
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

I understand that we have a base case of if (n <= 0){return 1} inorder for the code to not loop for ever but I dont understand the (n-1) and [n-1] in the recursive case of return multiply(arr, n - 1) * arr[n - 1]; .

Any help is much appreciated.

CodePudding user response:

It looks like this function is meant to start with the last element of the array and recursively operate on each earlier element. This is why when calling the function recursively, you must pass in the next earlier element, i.e. n -1. This moves the function closer to the base case with each iteration.

CodePudding user response:

This function just multiplies all elements of the given array. Initially you must pass the array and it's length as n.

The last element for any array is n-1. Thus on the 1st iteration it will take the last element and multiply further until it reaches 0. Then it will stop.

Just try to run this function mentally in your head on some simple examples and you'll get it.

CodePudding user response:

The function could be improved, but you can understand it as-is by adding some debug logging...

function multiply(arr, n) {
  if (n <= 0) {
    return 1;
  } else {
    console.log(`recurse to multiply ${arr[n-1]} by elements in [${arr.slice(0,n-1)}]`);
    return multiply(arr, n - 1) * arr[n - 1];
  }
}

multiply([1, 2, 3], 3);

A clearer implementation wouldn't require the length param, and be clearer about decomposition...

// if the array has a first element, multiply it by the remainder of the array
function multiply(arr) {
  return arr.length ? arr[0] * multiply(arr.slice(1)) : 1;
}

console.log(multiply([1,2,3]))

  • Related