0

I want to understand this below recursion. Here times-1 is passed each time function is called. How it reaches to zero? I mean, when times-1 is compared by if(times===1) then the statments terminates and else is not executed. And how each time decremented value is passed.

function repeatStringNumTimes(string, times) {
  if(times < 0) 
    return "";
  if(times === 1) 
    return string;
  else 
    return string + repeatStringNumTimes(string, times - 1);
}
repeatStringNumTimes("abc", 3);
Sanaullah
  • 29
  • 2
  • it doesnt reach 0 if you pass in a value greater than 0, the first check is probably for when you pass in a value less than 1 – Chris Li May 01 '21 at 17:15
  • Welcome to SO! You're correct, it doesn't ever run the `return ""` if `times` is greater than 0 for the initial call. This is a safety precaution to avoid blowing the stack if called with 0 or less. BTW, this is OK as a teaching example but is a poor fit for recursion otherwise. – ggorlen May 01 '21 at 17:15
  • 1
    it can be simplified to `if (times <= 0) return ""; else return string + repeat(string, times - 1)`. See [this Q&A](https://stackoverflow.com/a/67337190/633183) for additional explanation. – Mulan May 01 '21 at 18:40

0 Answers0