Basic Algorithm Scripting - Repeat a String Repeat a String

Tell us what’s happening:

In the Solution 2 given, the program will run but it is not totally correct.

function repeatStringNumTimes(str, num) {
if (num < 1) {
return “”;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}

if you try console.log(repeatStringNumTimes(“abc”, )); you will see the error througt in the console.

you can fix it by adding “num === undefined”

function repeatStringNumTimes(str, num) {
if (num < 1 || num === undefines) {
return “”;
} else {
return str + repeatStringNumTimes(str, num - 1);
}
}
or just change it like this:

function repeatStringNumTimes(str, num) {
if (num > 0) {
return str + repeatStringNumTimes(str, num - 1);
} else {
return “”;
}
}

Am I correct on it?
Your code so far

/*function repeatStringNumTimes(str, num) {
  return num > 0 ? str + repeatStringNumTimes(str, num - 1) : '';
}*/

function repeatStringNumTimes(str, num) {
  if (num > 0) {
    return str + repeatStringNumTimes(str, num - 1);
  } else {
    return "";
  }
}



repeatStringNumTimes("abc", 3);

console.log(repeatStringNumTimes("abc", 3));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Repeat a String Repeat a String

Link to the challenge:

The code for the second solution works fine as far as I can see. It’s just a basic recursion.
Of course, if you try to call the function without supplying a num argument, it won’t work, but the challenge doesn’t explicitly specify that you should cover this eventuality.
The alternative you suggest is the same recursion but with the if condition switched.

EDIT: I suppose you could interpret ‘not a positive number’ as including anything which isn’t a number (such as undefined), though it doesn’t cover the possibility that a user could enter 3.14159 either.

Thanks for your message and explanation.