Could anyone here help me by show what is error in this code?
function repeatStringNumTimes(str, num) {
if(num < 0){
return "";
}
else{
for(var i=1;i <=num;i++)
{
str ++;
}
return str;
}
}
repeatStringNumTimes("abc", 3);
....
++
increments a number by 1. A string isnāt a number, so str++
evaluates to NaN
(not a number).
Use the +
operator (or +=
) for string concatenation.
1 Like
You could also use the built in repeat method.
function repeatStringNumTimes(str, num) {
if(num < 0){
return "";
}
else{
return str.repeat(num);
}
}
repeatStringNumTimes("abc", 3);
1 Like
thanks for your help guys
Thatās a nicer, more concise way of doing it with ternary notation.
I donāt think you really need the ternary, as zero repeats returns an empty string.
You can write
function repeatStringNumTimes(str, num) {
return str.repeat(num)
}
But of course this is effectively just renaming ārepeatā.
The other interesting thing you can do is call the function recursively (functional programming!)
function repeatStringNumTimes(str, num) {
if (num < 1) {return āā;} else {return str + repeatStringNumTimes(str, num-1);}
}
This one fails test case repeatStringNumTimes("abc", -2)
.
1 Like