Returning an empty string

Can anyone explain why the following code is not returning an empty string if argument is not positive? This code relates to the following challenge:

https://www.freecodecamp.org/challenges/repeat-a-string-repeat-a-string

function repeatStringNumTimes(str, num) {
// repeat after me

var finalString = str.repeat(num);

if(num < 0){
finalString = β€œβ€;
}else {
return finalString;
}
}

repeatStringNumTimes(β€œabc”, 3);

If you look at the flow of your function when num < 0. You have:

finalString = "";

And nothing is returned.

2 Likes

MDN, your Lord and Savior can help understand what is happening here !

str.repeat(count);

Count an integer between 0 and +∞: indicating the number of times to repeat the string in the newly-created string that is to be returned.

It will raise
RangeError repeat count must be non-negative.
RangeError repeat count must be less than infinity and not overflow maximum string size.

So if you don’t encapsulate the str.repeat() with a try/catch, then on negative numbers you will have the exception raised and the code will stop :slight_smile:

1 Like