skip to Main Content

Why does this recursive function work?

let arr = []

function rep(x, n) {
  if (Math.sign(x) === -1) {
    return []
  }

  if (x < 1) {
    return 1
  } else {
    rep(x - 1, n)
  }
  arr.push(n)
  return arr
}

console.log(rep(5, 5))

I’m learning JS and about recursive functions. I made the above function to output an array of x, n number of times in an array. E.g. rep(2,5) would output [5,5], rep (3,3) would output [3,3,3] etc. But I don’t fully understand why it works.

Am I right in thinking that the last thing the function does is return the completed array? If so, why does it not return [] or 1 when x goes to -1? I think I’m confusing myself but I’d appreciate an clear explanation. Thanks

I created the above function and was not expecting it work. So, I made it but I don’t fully understand why it works.

2

Answers


  1. If so, why does it not return [] or 1 when x goes to -1?

    It does. But think about where it returns that to and what that bit of code does with it next.

    You only ever log console.log(rep(5, 5)).

    You don’t log the response at any point where x is -1.

    You would probably benefit from stepping through the code with a debugger.

    Login or Signup to reply.
  2. When you call rep(5,5), it gets called recursively as below:

    rep(5,5)
        rep(4,5)
            rep(3,5)
                rep(2,5)
                    rep(1,5)
    

    When x = 1, the below condition is satisfied and causes the recursion to stop. So,

      if (x < 1) {
        return 1
      }
    

    So, the below code does not get executed as Math.sign(x) never equal to -1

    if (Math.sign(x) === -1) {
        return []
    }
    

    However, if you run call rep(-3, 5), the above condition is satisfied and you will get [] as the output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search