Repeat a string repeat a string help

The results in the console seem to be correct, but it won’t pass me as right. Does anyone have any idea’s to slightly modify my code to get it run this way?

function repeatStringNumTimes(str, num) {
  if (num >= 1 ){
    for (var i = 0; i < num; i++){
    str += str;
  }
    return str;
  }

  else {
    return "";
  }
}

repeatStringNumTimes("abc", 3);

just some observations: 1: your function should return just one and only one time .
2: your for loop is not correct as its body doesnt contains the counter i

I’m getting incorrect results in my console. You implementation is wrong. Remember that str is changing on each loop. The first loop it adds str to str and you end up with “abcabc”. on the second loop, it adds str to str again, but str is no longer “abc”, now it is “abcabc” so you get “abcabcabcabc”. On the third loop, it doubles it again and you get “abcabcabcabcabcabcabcabc”.

To make your code work, you need a variable like finalStr, holder string that starts out as “” and you add str to it each time and return that - that will work. And since you initialize that holder string as “”, you don’t need an else statement for if num <1. I could right it out for you but you’ll learn more if you do it and it isn’t that tough. Check back if it’s too much.

1 Like