Problem:
Repeat a string numerous times.
This function input:
repeatStringNumTimes("abc", 3);
gives us this output:
abcabc
One of the way to achieve this:
Step 1
create a local variable equal to an empty string in order to have an empty container where to store all the string we are going to create:
let accumString = ""
Step 2
Create an iteration through a while loop
while ( num > 0 )
--> attention is a potential infinite loop
Step 3
Under the while loop condition fill up the variable using the addition assignment operator +=
accumString += str
Step 4
to avoid the infinite loop just created associate to num
the decrement operator --
to stop the loop when num
is 0.
note: the while loop is completed and we can close the curly bracket.
Step 5
Outside of the while loop but still inside the function insert the return statement to stop the function and return the value of the function.
Step 6
Now call the function repeatStringNumTimes("abc", 3)
with inside a random string and integer.
the output will be: abcabc
The whole function just created below:
function repeatStringNumTimes(str, num) {
let accumString = "";
while ( num > 0 ){
accumString += str;
num--;
}
return accumString;
}
repeatStringNumTimes("abc", 3);
Top comments (0)