Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
In this code there is no execution code to make out put to multiply elements in the array. So how the out put same to following code? Can anyone explain please.

function multiply(arr, n) {
    let product = 1;
    for (let i = 0; i < n; i++) {
      product *= arr[i];
    }
    return product;
  }

Your code so far

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

Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 13; SM-A525F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Mobile Safari/537.36

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

checkout this explanation and see if this is comprehensible, otherwise look into “recursive functions”

The recursive version of multiply breaks down like this. In the base case, where n <= 0 , it returns 1. For larger values of n , it calls itself, but with n - 1 . That function call is evaluated in the same way, calling multiply again until n <= 0 . At this point, all the functions can return and the original multiply returns the answer

happy learning :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.