Recursion: What is actually happening here?

You won’t continue to the next line until the (recursively called) function returns.
countup(n -1) will return a value when it is done running. It will be assigned to countArray and then countArray.push(n) will execute.

2 Likes

Every time you call a function, the function goes though its logic. There is no ‘go back’ like a loop. Each function call is independent.

countup(5) calls countup(4)
  countup(4) calls countup(3)
    countup(3) calls countup(2)
      countup(2) calls countup(1)
        countup(1) calls countup(0)
          countup(0) returns []
        countup(1) can now take this result and push(1)
        countup(1) returns [1]
      countup(2) can now take this result and push(2)
      countup(2) returns [1, 2]
    countup(3) can now take this result and push(3)
    countup(3) returns [1, 2, 3]
  countup(4) can now take this result and push(4)
  countup(4) returns [1, 2, 3, 4]
countup(5) can now take this result and push(5)
countup(5) returns [1, 2, 3, 4, 5]
12 Likes

ah I finally get it … (I hope so) … the “secret” is “It will be assigned to countArray” … in fact we will stock the value of countup(n-1), (n-2) etc … in the countArray even though we didn’t push anything yet. Am I right ?

Yeah. The call to countup(n - 1) will return an array. That array might just be [] (if n is 1) or it will be the result of n recursive calls that have “bubbled up”. If n is 3, then countup(n - 1) will return [1, 2], for example.

2 Likes

Thank you a lot guys … you really shed light on this dark subject

I’m glad we could help. Recusion is often one of those things that you need to approach with new eyes a couple times before it “clicks”.

2 Likes