I do not know how it works about these codes?

Here is “learn-recursion-by-building-a-decimal-to-binary-converter/step-65”,
I was confusing about how the funciton run, do not know why.
like below codes that I tried to find out, but no result.

onst countDownAndUp = (number) => {
  console.log(number+"@@@@");

  if (number === 0) {
    console.log("Reached base case");
    return;
  } else {
    countDownAndUp(number - 1);
    console.log(number+"****");
  }
  console.log(number+"!!!!");
};

countDownAndUp(3);

The console.log results is bellow:

3@@@@
2@@@@
1@@@@
0@@@@
Reached base case
1****
1!!!!
2****
2!!!!
3****
3!!!!

THe first question is:
how the funtion “countDownAndUp()” run, why the result is "
1****
1!!!
2****
2!!!
3****
3!!!
"
after “Reached base case”?

The second question is , what “Return;”'s , how it works here? Because, if I delete it. the result will be changed like this"
0!!!
1****
1!!!
2****
2!!!
3****
3!!!
"
Sorry for the inconvenience if I do not type correctly for the question.
Thank you all in advanced.

I suggest running the function for just the value 1. What happens? You should see it log:
1
0
Reached base case
1

Why?
Because when the if function is false and the else takes over, it calls the function again, which effectively pauses that first run through. Once the second run finishes (remember that even though it isn’t included at the end of the function, the return is implied), the first run starts up again right where it left off.

Pretend the function is written on a notecard. Every time the function calls itself, put another notecard on top of the first notecard. Do this until you finally stop putting down a new notecard and can finish and remove each notecard one by one.

Thank you very much, I tried the value 1, and know the function well, and also know that after functon (within the else) running, the follow statement would running (console.log(number);), so there will be a “1” showing up. But if I tryied that the value is 2, where is the last vaule “2” coming from?

2
1
0
Reached base case
1
2

BTW, I know what you mean, and I also study something about recursion on Google, and also know what recursion is(hope I really knew), but I also still can’t thing about it deeply.

I suddenly know what that meaning about you gave the example of notecard,
this statement (countDownAndUp(number - 1):wink: will be callback itself automatically, so i will be produce 1 and then 2,
it is automatic.

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