Tell us what’s happening:
Hi, having problem with the loop here. console shows that the string was repeated only once. Not sure what went wrong. can someone help me?
Your code so far
function repeatStringNumTimes(str, num) {
if (num <= 0){
return str= "";
} let result = str ;
for (let i = 0; i <= num; i++){
result = str.concat(str);
}
return result
}
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/72.0.3626.121 Safari/537.36.
It’s because str doesn’t ever change – you concatenate str to itself, assign it to result, then the next time through the loop, the same thing happens with the same str value. Do you see the problem now?
str.concat(str) just returns str concatenated to str, but doesn’t change str in any way. Each time you go through the loop, you assign it to result. What you want to do is to concatenate result to itself, then assign it to result, which will update the value of result.
Oh, I made a mistake myself. What you want is each time through the loop, append str to result, not result. Otherwise you’re doubling it each pass. My bad.
now take a look at the condition of your loop and at the starting value of result, you will have a final strin longer than you want with things like that. Just using starting value of 0 and final value of i <= num will add at least an extra repetition
haha, that’s okay, It seems to be working fine now, I had to initialize the loop variable as 1 as well, because it seems like the repetition times should be the second number minus one.