Repeat a string help

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);

....

++ 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.

1 Like

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);
1 Like

thanks for your help guys

Orā€¦

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

:wink:

1 Like

Thatā€™s a nicer, more concise way of doing it with ternary notation.

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);}
}

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

1 Like