Repeat a String Repeat a String Problem?

Tell us what’s happening:
Can anyone tell me why this isn’t working? My only suspicion is that the string created from my array doesn’t qualify as a repeated string. The function itself seems sound, as it runs the for loop [num] times and pushes it to [array], which I join( into a single string again. Feedback welcome, thanks!

Your code so far


let array=[];
function repeatStringNumTimes(str, num) {
  // repeat after me
  for (let i=0;i<num;i++){
  array.push(str);
}
return array.join('');
}
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/76.0.3809.132 Safari/537.36.

Link to the challenge:

Hello
remove this line

let array=[];

from the globale scope and put it inside the function scope.

1 Like

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

Thank you for explaining! Makes perfect sense.

Glad to help. Happy coding!