Repeat String Help me understand my own code!

Tell us what’s happening:

Hi Please someone help me understand the code below which I’ve hacked together. it works but I cant get my head around why ‘i’ needs to be initialized at 2.
its crazy that I solved it but don’t understand my own solution. :sweat_smile:


function repeatStringNumTimes(str, num) {
if (num <= 0){
  return "";
}else{
let copyStr = str;
for (let i = 2; i <= num; i++){
  copyStr += str;
}
  return copyStr;
}

}
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/85.0.4183.102 Safari/537.36.

Challenge: Repeat a String Repeat a String

Link to the challenge:

you start with one copy of the string here

so if number is 3:

before loop:
copyStr = str;

i = 2
copyStr = strstr

i=3
copyStr = strstrstr

if you initialize i at a lower value, you get extra unwonted copies

1 Like

ohh so by copying a string prior I have already initialized once hence it needs to be initialized from 2 right?