-1

I am writing a program to concatenate a string to make it repeat a number of times but on using concat method it always returns an empty string. I have solved the problem using + operator. But I still want to figure why concat is returning empty string.

Here is the code

let repeatStr = (str, num) => {
    let newStr = '';
    for(let i = 0; i < num; i++){
        newStr.concat(str); 
    }
    return newStr;
}
3
  • 1
    You need to use the return value of concat() Commented Jul 18, 2021 at 18:58
  • 2
    BTW incase you didn't know, you can just use the String.prototype.repeat function to repeat a string rather than creating a new function Commented Jul 18, 2021 at 19:02
  • 1
    Duplicate of String Concat not working in scope JS. Commented Jul 18, 2021 at 19:38

3 Answers 3

1

I believe it is because concat method does not modify the string in-place, and you need to assign its result to some variable. If instead you replace that line in your code with newStr = newStr.concat(str); it should work fine.

Sign up to request clarification or add additional context in comments.

Comments

1

This is because .concat() returns a new string, and the original is unmodified. You can reassign to the same variable.

Note: You can also use the + operator.

let repeatStr = (str, num) => {
    let newStr = '';
    for(let i = 0; i < num; i++){
        //newStr = newStr.concat(str); //Both work
        newStr += str;
    }
    return newStr;
}

console.log(repeatStr('x',3));

3 Comments

concat returns with string not array
@Joseph Yup, this applies for string. Changed the wording. Btw, concat is method on both the string and array prototype. And it returns the new value in both the cases.
Yeah, you are right but in this case, you are talking about string not array
0

If you check the definition of concat in MDN

The concat() method concatenates the string arguments to the calling string and returns a new string.

that is means that it doesn't change the old value of your variable so all you need is to re-assign your variable with the new value

let repeatStr = (str, num) => {
    let newStr = '';
    for(let i = 0; i < num; i++){
       newStr = newStr.concat(str); 
    }
    return newStr;
}

console.log(repeatStr('welcome', 2))

there is another simple solution you could use repeat function it used for this purpose like this

console.log("welcome".repeat(3))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.