Help understanding recursion concept

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?

1 Like

multiply(arr, n) means ‘the product of the first n things in the array’

arr[n-1] is the nth thing in the array

multiply(arr, n-1) is the product of the first n-1 things in the array (zero based indexing!)

The product of the first n items is certainly the product of the first n-1 items multiplied by the nth item

That statement doesn’t require you to deeply understand recursion, just multiplication

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.

Note to self:
multiply(arr,3) = arr[2] * multiply(arr,2)
multiply(arr,3) = arr[2] * arr[1] * multiply(arr,1)
multiply(arr,3) = arr[2] * arr[1] * arr[0]


Hey @wryyyy!

Welcome to the forum!

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.

Thank you Jessica! I will install VS Code and get acquainted with using it, as well as debugging. I’ve been relying on the FCC console and console.log

1 Like

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.