Repeat a String assignment, solved but won't pass

Tell us what’s happening:
I solved the Repeat a String Repeat a String assignment where you pass a str and num as arguments and return the number of characters in the str. My solution passes all the requirements, but it won’t pass the assignment. Can someone tell me why?

  **Your code so far**

let newStr = "";
function repeatStringNumTimes(str, num) {
if (num <= 0) {
  return "";
} else {
  newStr = newStr + str;
  repeatStringNumTimes(str, num-1);
}
return newStr;
}

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/97.0.4692.99 Safari/537.36

Challenge: Repeat a String Repeat a String

Link to the challenge:

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2
1 Like

Ah, I see. But when I declare the variable within the function, it resets every time the function is recurred. So I guess that means I chose the wrong way to solve the problem, and I need to go a totally different route, or am I close with this strategy and just missing something obvious here?

You can use recursion, but you would need to use the return value from the recursive call.

1 Like

Ah, yes! That makes sense and solves it. Thanks for the help!

1 Like