Repeat a String Repeat a String question about for loop

I’m wondering how total total += str is using the for loop when I havent assigned i to str or total.

  **Your code so far**
function repeatStringNumTimes(str, num) {
let total = '';
for(let i=0; i<num; i++){
  total += str
    }
return total;
}

console.log(repeatStringNumTimes("abc", 3));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36

Challenge: Repeat a String Repeat a String

Link to the challenge:

The code inside a for loop will run as many times as the condition is true, you don’t need i to be in there at all for it to run. So while i is less then num, the loop will execute the code as many times as that is true. And inside your for loop you are telling total to equal total + str. So if it runs three times, str will be added to total 3 times.

2 Likes

total += str is a shorthand for total = total + str
You initialize total with a value of an empty string. Then you run a for loop, which would repeat times equal num. Since you add str to total every loop, this is gonna exectute num times. In the end you will return the final value of total

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.