How to Repeat a String in JavaScript Without Using a Loop?

Using String.repeat() to Repeat a String

Introduced in ES6, repeat() function allows us to specify a count to create a new string with the specified number of copies, concatenated together, of the string on which it was called.

Following are a few examples that show how it works:

// ES6+
'foo'.repeat(0); // ''

'foo'.repeat(1); // 'foo'

'foo'.repeat(3); // 'foofoofoo'

'foo'.repeat(3.9); // 'foofoofoo'

'foo'.repeat(-1); // RangeError

Note that the count parameter for the repeat() function only takes positive integers between 0 and +Infinity. Therefore, fractions are converted to integers, and negative numbers or overflowing maximum string size throw a RangeError.

Using Array.join() to Repeat a String

To repeat a string n number of times with Array.join(), we would need to create an array of length n + 1 and use join() like so:

Array(3).join('foo'); // 'foofoo'

From the example above, you might have noticed that to repeat the string two times, we had to create an array of length 3. This is because of the way join() works. It is normally used to concatenate elements of array together, and it repeats array.length - 1 times since the concatenation happens between the array elements and the last element of array has nothing at the end of it.

Another important thing to understand here is that, when we use the Array() constructor to create a new Array object of a specified length, it creates the array with empty slots. So when we use join(), it concatenates empty array elements with the specified string, leaving us with only the repeated string we supply to join() for "concatenation".

Although this is a bit of a hacky way to repeat a string, still it might be a good substitute to String.repeat()(that doesn't use a loop) if your support target is below ES6. Especially because it has great browser support.

Now, with that out of the way, let's look at a few more examples:

Array(0).join('foo'); // ''

Array(1).join('foo'); // ''

Array(3).join('foo'); // 'foofoo'

Array(3.9).join('foo'); // RangeError

Array(-1).join('foo'); // RangeError

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.