Basic algorithm: Repeat a String. loop problem

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.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string

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?

So the str value would not be updated in the next round?

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.

Hopefully I made it a little clearer…

here, concat() doesn’t mutate original thing. so you can at most have it repeated it twice becousa you always say str.concat(str)

I suggest concatenation with the + operator

or using concat() as said above will work too

Thanks, I just did exactly as you said, but something is still off… console shows that result has been repeated far more than required??

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.

first iteration:

result = result.concat(result);

result is now "abcabc"
second iteration, result becomes "abcabcabcabc" because you concat current value of result

You dont want to do that, you will need something else in that line

now changed it to result equals result concatenate str, still didnt work. Is this what you meant?

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

Starting from 0 and using < should also be correct. Using 0 and <= will result in an extra concatenation.

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.

if you do well your loop you don’t even need this part

that’s because you initialize your result as result = str