Repeat a string help

Repeat a string help
0

#1

Could anyone here help me by show what is error in this code?


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

repeatStringNumTimes("abc", 3);

....

#2

++ increments a number by 1. A string isn’t a number, so str++ evaluates to NaN (not a number).

Use the + operator (or +=) for string concatenation.


#3

You could also use the built in repeat method.

function repeatStringNumTimes(str, num) {
  if(num < 0){
    return "";
  }
  else{
      return str.repeat(num);
}  
}

repeatStringNumTimes("abc", 3);

#4

thanks for your help guys


#5

Or…

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

:wink:


#6

That’s a nicer, more concise way of doing it with ternary notation.


#7

I don’t think you really need the ternary, as zero repeats returns an empty string.

You can write

function repeatStringNumTimes(str, num) {
return str.repeat(num)
}

But of course this is effectively just renaming ‘repeat’.

The other interesting thing you can do is call the function recursively (functional programming!)

function repeatStringNumTimes(str, num) {
if (num < 1) {return “”;} else {return str + repeatStringNumTimes(str, num-1);}
}


#8

This one fails test case repeatStringNumTimes("abc", -2).