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.

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement