Returning an empty string

Returning an empty string
0.0 0

#1

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


#2

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

finalString = "";

And nothing is returned.


#3

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.


#4

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: