Undefined Variable thrown

3712 views javascript
6

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);
}

answered question

return str + repeatStringNumTimes(str, num - 1); is a recursive call. Concatenate str with the result of repeatStringNumTimes(str, num - 1);

Ah, ok. Duh... I feel dumb for asking that now. Thank you!

@kevin We don't put 'solved' in the question title here. To indicate the question is solved, click the outlined checkmark next to the answer.

1 Answer

11

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.

posted this

Have an answer?

JD

Please login first before posting an answer.