-1

so I am very new to js and I'm having a really hard time comprehending the language. Could anyone take 5 to look at this code and tell me why my function isn't working...? The goal is to create a function that duplicates a string by the number inputted into the function.

function repeatString(string, num) {
return string*num
}
var output=repeatString("Hello!",2);
console.log(output);
3
  • Why would that work? Guessing is not the way to go Commented Oct 9, 2017 at 19:51
  • the * operator, when used with a string and a number, results in NaN. Perhaps use String.concat (or string.repeat if you want to cheat) Commented Oct 9, 2017 at 19:51
  • function repeatString(s, num) { if(num > 1) { s += ' '+ repeatString(s, num-1); } return s; } Here is a recursive approach. Commented Oct 9, 2017 at 20:02

1 Answer 1

1

You could simply call the repeat method:

function repeatString(string, num) {
    return string.repeat(num);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You were faster! And here's the documentation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Be advised no versions of Internet Explorer support this, so a polyfill may be needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.