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: