Skip to content
Advertisement

How can I recurse in JS to repeat a string n times?

I am trying to make the code below repeat string s n number of times, however, it will always repeat n - 1 times, because I need to pass a decrement to exit the recursion or I will exceed the max call stack.

function repeatStr (n, s) {
  while(n > 1) {
   result = repeatStr(-n, s)
    return s = s.concat(s)
  }
}
repeatStr(3, "Hi")

What can I change to make it recurse correctly?

Advertisement

Answer

Recursion involves making a function call itself and AVOIDS using a loop. You have a loop in the recursive function which is a big red flag.

Do something like this: If n is 1 return s else return s concatenated to the result of the function with n – 1.

function repeatStr (n, s) {
   if (n == 1) 
       return s;
   else
       return s.concat(repeatStr(n - 1, s))
}
repeatStr(3, "Hi")
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement