0

I have this algorithm exercise that is very popular with developers that returns:

steps(3)

#
##
###

steps(5)

#
##
###
####
#####

I am studying a version of it developed in a recursive way. The code below is working fine.

function steps(n, row = 0 , stair = '') {
  if(n === row) {
    return;
  }

  if(n === stair.length) {
    console.log(stair)
    return steps(n, row + 1)
  }

  if (stair.length <= row) {
    stair += '#';
  } else {
    stair += ' '
  }
  steps(n, row, stair)

}

steps(3)

My only doubt is related to the importance of the 'return' in this part of the code:

 if(n === stair.length) {
   console.log(stair)
   return steps(n, row + 1) // <--- this 'return' 
 }

If I delete the 'return', like this way:

if(n === stair.length) {
  console.log(stair)
  steps(n, row + 1)  // <-- without the return
}

this generates a looping error on console:

Maximum call stack size exceeded

I want to understand why this happens under the hood. I still don't have much practice with recursive functions.

3 Answers 3

1

if n===stair.length, you don't want to make the call steps(n, row, stair) at the bottom of the function, which you would if you left out the return.

Sign up to request clarification or add additional context in comments.

Comments

1

There are kind of 2 ways to think about recursive functions. The first is to actually look at what literally happens -- that is, look at an example and "unroll" by noting all of the calls to the function steps. This is safe to think about and is easy.
The second way is more "magical. In this way of thinking, you do NOT consider a "big picture" or think about multiple calls of the recursive function. Instead, you form a coherent idea of what your recursive function SHOULD accept as arguments and what it SHOULD return. Then, you can always write the body of your recursive function by using that function in the way you assume it should work. This can be more confusing to grasp, but once you "get" it, it's very elegant and is the more useful mode of thinking.

Let's use the first mode of thinking here, since it's probably easier. Can you tell me how many times steps gets called and with which arguments, in order? For example, the first call is steps(5, 0, ''). Then, what is the second call of steps that will happen? Follow these steps (heh) and you should see what the issue is.

Comments

1

It breaks because your code terminates when row === n. That line is the only place where row is changed. Without it, the code will produce output like this:

#
#
#
#
#
...

Since you're handling this in a recursive function, javascript runs out of stack frames before it gets infinitely deep.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.