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:

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.


The repeat function requires the value passed to it to be 0 or greater. It errors out if it is not and the rest of your code does not run.

1 Like

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


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