Repeat a string questions

Repeat a string questions
0

#1

well i got it to work using assigment operates in my for loop but why doesnt this work

function repeatStringNumTimes(str, num) {
  // repeat after me
 str2="";
   for(i=0;i<num;i++){
     str2.concat(str);}
   

console.log(str2);
}



repeatStringNumTimes("abc", 3);

this wasnt my final one with the if statemenbt to produce the empty string if less then 0 but i just am curious why wont that work


#2

ah i think i figured it out thanks though


#3

It’s great you figured it out. Perhaps you could share your solution for other people that will come here looking for help :slight_smile:


#4

the solution came up with was

function repeatStringNumTimes(str, num) {
  // repeat after me
  
var str2=""; 
 if (num>0){
   for(i=0;i<num;i++)
     str2+=str;
   
 }else {return "";}
return str2;
}



repeatStringNumTimes("abc", 3);

but the inside of the loop could also be replaced with

str2 = str2.concat(str);


#5

Alternatively, you could go this approach:


function repeatStringNumTimes(str, num) {
 return num > 0 ? str.repeat(num) : '';
}

repeatStringNumTimes("abc", 3);