2

Why below block of code not output string ?

I was expecting it should display abc when we pass num=1.

What I am missing here ?

function repeatStringNumTimes(str, num) {
  return Array(num).join(str);
}
console.log(repeatStringNumTimes("abc", 1));

2
  • 3
    How can you join one item with no other items with a delimiter? Commented Aug 4, 2017 at 7:15
  • @mplungjan I understand now. Thanks a lot. Commented Aug 4, 2017 at 7:20

3 Answers 3

9

You need at least two elements for Array#join with a separator, because one element is just converted to a string and it does not need any glue.

function repeatStringNumTimes(str, num) {
    return Array(num + 1).join(str);
}
console.log(repeatStringNumTimes("abc", 1));

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

Comments

2

If you only need a string to be repeated n times, use ES6's String.repeat, like so:

'myString'.repeat(repeatTimes);

Or an array-based solution (not recommended for your problem, though):

new Array(repeatTimes).fill('myString').join('');

If you need ES5 solution, use lodash fn repeat:

_.repeat('abc', 2);

7 Comments

Fill is not supported by IE
You can always use a polyfill, which is found here: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
or just do Array(num + 1).join(str);
@davidxxx 6.2% for you - 10% for me -> 600K requests per week (IE7-15) - feel free to ignore IE. I certainly cannot and will not.
@mplungjan 6 or 10% are not significant. I don't say that we have to ignore IE in any case but this remark : "doesn't work on IE" doesn't make sense today in a general Q/A now as IE is not a standard any longer even in the companies. It was relevant 5 or 10 years ago. "doesn't work on Chrome" could make more sense today but as Chrome supports most of things to support, it is rather uncommon to hear it :)
|
-2

The correct way should be

str.repeat(num)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.