Repeat a string repeat a string (clarification)

Repeat a string repeat a string (clarification)
0.0 0

#1

So I’m just looking for a bit of clarification, because when I entered this code:


function repeatStringNumTimes(str, num) {
var a = str.repeat(num); 
if (num > 0) {
  return a;
}   
  else return "";
}

repeatStringNumTimes("abc", -2);

I got a RangeError: Invalid Count Value

but when I just changed the placement to this:

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

repeatStringNumTimes("abc", -2);

It worked just fine. Can someone please explain why this is?

Thanks for the help!!!


#2

The reason is explained by the error. The repeat function can only take numbers >= 0, so in the first solution, the -2 is not a valid number for the repeat number. In the second solution, you only use the repeat function if num > 0, so no error message.


#3

Ok, thanks @randelldawson. That explanation helps alot.