Tell us what’s happening:
Someone please help me out here.
First, I do not understand how the demonstrated for-loop code works. On top of that, I do not understand how the recursion code works and why it is a better alternative to the for-loop method. Please try to explain it to me in the simplest possible way
##Below is the problem
Basic JavaScript: Replace Loops using Recursion
Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the elements from 0
to n
inclusive in an array to create the product of those elements. Using a for
loop, you could do this:
function multiply(arr, n) {
var product = arr[0];
for (var i = 1; i <= n; i++) {
product *= arr[i];
}
return product;
}
However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n]
. That means you can rewrite multiply
in terms of itself and never need to use a loop.
function multiply(arr, n) {
if (n <= 0) {
return arr[0];
} else {
return multiply(arr, n - 1) * arr[n];
}
}
Your code so far
function sum(arr, n) {
// Only change code below this line
// Only change code above this line
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36
.
Challenge: Replace Loops using Recursion
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion