Concatenate a string as many times the for loop runs

Tell us what’s happening:
I want the for loop to run three times(or as many times is specified in the second parameter of the function). For some reason it is not working.
I want to concatenate the string as many times it runs in the for loop.

Your code so far


function repeatStringNumTimes(str, num) {

var str1 = str ; 
if(num < 0){

return "" ;

}else{

for(var i = 1 ; i<= num ; i++)
{
  var str2 =str.concat(str1);
}

console.log(str2);
}

}

repeatStringNumTimes("abc", 3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Repeat a String Repeat a String

Link to the challenge:

you need do define str2 outside the loop if you want to do this. Also, you are just always setting it to be equal to str.concat(str1), instead to change str2 based on previous value you need to have str2 = str2 ...

I did not understand the last part, about str2 …

let’s think of wanting to sum consecutive numbers, for example from 1 to 4
wouldn’t do you it like this?

var sum = 0;
for (var i = 1; i <= 4: i++) {
   sum = sum + i;
}

look at the calculation, we say that the new sum is equal to the old sum plus a number
you need to do something similar to build your desired string

2 Likes

@ILM

var str2 ;
  for(var i = 1 ; i<= num ; i++)
  {
    str2 = str.concat(str2);
  }

The above code runs and gives me abc three times but also concatenates undefined.

output:
abcabcabcundefined

because the starting value of str2 is undefined, you need to set it to something, even an empty string

2 Likes