Repeat String Exercise Question

Hey guys, started working on this exercise and want to better understand why my first solution didn’t work and the second did. Here is the first.

const repeatString = function (str, numOfTimes) {

let finalString = '';

for (let i = 0; i < numOfTimes; i++) {
   finalString.concat(" ", str);
}
return finalString;

}

Here is the second that worked.

const repeatString = function (str, numOfTimes) {
let finalString = ‘’;

for (let i = 0; i < numOfTimes; i++) {
    finalString += str;
}
return finalString;

}

From reading the documentation for concat(), shouldn’t it do the same thing as +=? Perhaps i’m not understanding correctly. Appreciate the help.

Hi the problem seems to be the concat funtion. This function doesnt modify the strings only return an output with the strign concatenated.

You but you can save the result in the same string.

  finalString=finalString.concat(" ", str);

this do the same thing that +=

Hope this will help.

2 Likes

@fernandopaz1 I love this answer. It reminds me as a JavaScript beginner to always read up on the return value of any function I learn about or find out. I have done these fundamentals and that tip saved me some headache, but could have saved even more if I started applying it earlier.

2 Likes

This helps. Thanks!