Hello! I am currently on “Basic JavaScript: Replace Loops using Recursion” and am having a hard time understanding a particular observation.
It provides an example of how you can multiply n elements in an array, by using a for loop, to create the product. This is the code provided:
function multiply(arr, n) {
var product = 1;
for (var i = 0; i < n; i++) {
product *= arr[i];
}
return product;
}
It then goes on to say the following:
However, notice that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1] .
This is the ONE statement that lost me, and I am not able to conceptualize this information. How does one arrive at the conclusion that multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1], without yet being familiarized with recursion?
I understand how recursion works on a simpler scale (ex. a countdown), but not in this particular situation. Can anyone please elaborate on how I can test this?
Thank you so much for your quick and helpful response! My train of thought was headed in the wrong direction. Your explanation put me on the right track. Substituting a number in for n helped me understand what the statement was trying to say, given your clarifications.
I am a beginner too and recursion was tricky at first when I started learning. Another tool that can help you is to use a debugger on your recursive functions.
For me, if I get confused on what a function is doing then I open up my debugger in vs code and run it to see exactly what is happening step by step.
You can also use other debuggers in different code editors, chrome developer tools and IDE’s. VS code is just my personal choice. There is a section on debugging in the FCC curriculum.