# Basic JavaScript - Replace Loops using Recursion

Tell us what’s happening:
Describe your issue in detail here.
I don’t understand this code, it’s quite confusing

``````  **Your code so far**
``````
``````function sum(arr, n) {
// Only change code below this line
if (n <= 1) {
return;
} else {
return sum(arr, n - 1) * arr[n - 1];
}
// Only change code above this line
}
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Linux; Android 8.1.0; vivo 1908) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.104 Mobile Safari/537.36`

Challenge: Basic JavaScript - Replace Loops using Recursion

Link to the challenge:

what is it that you don’t understand?

that looks similar to the code given in the example in the exercise:

in your case you are returning undefined as that is what it will do since you didnt specify anything to return reguarding what you wrote:

``````if(n<=1){
return
}
``````

for the example given in the exercise the function is being called repeatedly with a lesser value of n each time. when it is less than or eqaul to zero it returns 1, that will in turn be multiplied by what was above it in the stack until they all pop off the stack. (keep in mind that it will stop at the recursive calls and go all the way in until it is resolved before the code can advance to *arr[n-1] for example:

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

console.log(multiply([2, 3, 4, 5], 3))

//multiply([2, 3, 4, 5],3)  * arr[3]
// multiply([2, 3, 4, 5],2)    *arr[2]
//   multiply([2, 3, 4, 5],1)     *arr[1]
//      multiply([2, 3, 4, 5],0)     *arr[0]

//      multiply([2, 3, 4, 5],0)     *2     // (1*2) =2
//   multiply([2, 3, 4, 5],1)     *3    //(2*3) =6
// multiply([2, 3, 4, 5],2)    *4    //(6*4) = 24

``````

does either of these make sense?

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

function multiply(arr, n) {
let i=0
let val=1
while(i<n){
val*=arr[i]
i++
}
return val
}
``````

they are doing the same thing. instead of a loop or a while that runs as long as the condition inside the parentheses is true you should replace that with calling the function itself with a changing parameter and a base case to prevent it from running ad infintium

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