Reputation: 3498
This is a freecodecamp problem where the string argument should be multiplied by the num argument. I understood the other methods they provided, but I'm hung up on how this one works.
repeatStringNumTimes("abc", 3);
//should return "abcabcabc"
I am trying to figure out how the last part of this function (the else statement) inherently knows to multiply the parameters together even though there is no instruction to do so. The way I see it, all it says is: x + (x, y - 1) yet somehow it's still returning correctly.
What am I missing?
function repeatStringNumTimes(str, num) {
if(num < 0)
return "";
if(num === 1)
return str;
else
return str + repeatStringNumTimes(str, num - 1);
}
Upvotes: 0
Views: 49
Reputation: 582
This is a form of computing called "recursion". It refers to functions that can refer to themselves, thus restarting their cycles until a certain condition is met. In this case, the function is recursively calling itself num
times, which in this case yields a simple repetition of its commands.
Upvotes: 1