Repeat a string repeat a string (clarification)

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!!!

Ok, thanks @camperextraordinaire. That explanation helps alot.

1 Like