How to console.log and understand recursive function returns?

Tell us what’s happening:

I’m trying to make sense of the function in the example, that multiplies the elements from 0 to n inclusive in an array to create the product of those elements.
In my understanding, it starts from the n-th array element, which in my case is 6, multiplies it by the (n-1)-th element, which is now 5 and iterates until n = 0.
Is there a way to log the return of every iteration? I would like to see something like this:
30
120
360
720

Your code so far


function multiply(arr, n) {
    if (n <= 0) {
      return arr[0];
    } else {
      return multiply(arr, n - 1) * arr[n];
    }
  }
console.log(multiply([2, 3, 4, 5, 6, 7, 8, 9], 4));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 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

Try console.log(n) as your first line inside a function

you can also do (substitute the right function name there!)

let result = functionCall() * arr[n];
console.log(result);
return result;
2 Likes

Thank you, magical! I wonder if I have done it right. My logs make me very confused:

function multiply(arr, n){
  if (n<=0){
    return arr[0];
  } else {
    let result = multiply(arr, n-1) * arr[n];
    console.log(result);
    return result;
  }
}
console.log(multiply([2, 3, 4, 5, 6, 7, 8, 9], 4));

// console output

6
24
120
720
720

Does the function iterate 6, 5, 4, 3, 2, but multiply 2, 3, 4, 5, 6?

try looking at this one, with console log included, with this tool to see what happens

http://pythontutor.com/javascript.html#mode=edit

4 Likes

Wow, that’s awesome! Visualizing what you do totally rocks!

As of the diagram, we do know n value at every iteration, which lets us always know arr[n] value; and once n<=0, the first return value is used to calculate every upper-level function return value.
It’s not obvious to me what value n (block 1) is and why is it undefined?

I have gone through a similar process with a pen and paper. I wonder if I got it right :slight_smile:

That’s no code, the format is just for better readability.

function multiply(arr, n) {
    if (n <= 0) {
      return arr[0];
    } else {
      return multiply(arr, n - 1) * arr[n];
    }
  }
console.log(multiply([2, 3, 4, 5, 6, 7, 8, 9], 4));

What happens once the function runs:

function multiply([2, 3, 4, 5, 6, 7, 8, 9], 4)){  // let it be level 0 
  if (4<=0){ // which is false
    return 2; // which is arr[0]
  } else { 
    return multiply([2, 3, 4, 5, 6, 7, 8, 9], 3)) * 6; 
    // n=4, so arr[n]=6 here; n-1=3 will be passed down as n;  
} 
      // to yield the result, the function goes on to evaluate if n<=0 again at level 1: 
      if (3<=0){ // which is false
       return 2; // which is arr[0]
      } else {
         return multiply([2, 3, 4, 5, 6, 7, 8, 9], 2)) * 5; 
      // here n=3, so arr[n]=5; n-1=2 will be passed down as n;
      } 
          // this initiates level 2:
          if (2<=0){ // which is false
           return 2; // which is arr[0]
          } else {
            return multiply([2, 3, 4, 5, 6, 7, 8, 9], 1)) * 4; 
            // here n=2, so arr[n]=4; n-1=1 will be passed down as n;
          } 
              // this initiates level 3:
              if (1<=0){ // which is false
                return 2; // which is arr[0]
              } else {
                return multiply([2, 3, 4, 5, 6, 7, 8, 9], 0)) * 3; 
              // here n=1, so arr[n]=3; n-1=0 will be passed down as n;
              } 
                // this initiates level 4:
                if (0<=0){ // which is true, finally!
                  return 2; // which is arr[0]
              }

Once the function at the bottom level returns a value, it stops being executed, and its return value is used to get the return value of the previous-level instance of the function. If-condition never gets to be evaluated again at any level.
Now we go back up:
level 4 returns 2;
level 3 returns 23=6;
level 2 returns 6
4=24;
level 1 returns 245=120;
level 0 returns 120
6=720;

2 Likes

it should be result but the tool seems to have issues with variables declared with let
it is undefined because the line in which its value is defined has not yet finished running, once the recursive called functions will start having an output, you will see those variables having a value


your breakdown of the code is spot on!

Thank you!
I hope your day rocks!

Hi, I was also stuck on trying to understand how this works. I used that visualization tool which was great, thanks for sharing. I understand how the function calls itself until it returns the value, but I don’t quite understand how this entirely works when we return and multiply it. Anyways, I guess its really hard to explain this logically but we just need to know what it does. To be honest, I thought the curriculum did not explain this well and it seems complex for a beginner.

1 Like

what part do you not understand? take a look at others topics on this too, it has been explained a few times in really long posts, in different ways, maybe one of those click with you

I didn’t understand how exactly the blocks work, like why it goes back up the blocks after returning the result. But I was able to complete all the challenges and now I understand it better. Those blocks remain un-executed so when we return the result the function does not call itself from the top but instead evaluates those remaining blocks and logs each result.

1 Like

I don’t think some people are thinking simple enough.

<solution redacted>

@antonysoflo

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

2 Likes

A post was split to a new topic: Basic JavaScript: Understanding Recursion Example