String.prototype.repeat()
Small and predictable, with one sharp edge: most string methods clamp or ignore bad arguments, and this one throws.
Demo
Straightforward until the last case. Zero copies give an empty string, which is the sensible answer and the one most code relies on. A negative count, though, is a RangeError rather than an empty string — unusual for a string method, since slice, padStart and the rest all clamp silently. If the count comes from arithmetic that could go negative, guard it with Math.max(0, n) or you will get an exception instead of a harmless empty string.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| count | number | yes | How many copies. Truncated toward zero, so 2.9 means 2. Must be zero or more and finite — anything else throws RangeError. |
Return value
string — The string concatenated with itself count times. Zero gives an empty string; a negative count throws RangeError.
Common patterns
console.log('-'.repeat(60));
const indent = ' '.repeat(Math.max(0, depth));
const padded = s + ' '.repeat(Math.max(0, width - s.length));
Examples
Pitfalls
' '.repeat(10 - 'a very long string'.length)
' '.repeat(Math.max(0, 10 - s.length))
let s = 'ab'; s.repeat(3); s
let s = 'ab'; s = s.repeat(3); s
'x'.repeat(userSuppliedCount)
'x'.repeat(Math.min(1000, n))
' '.repeat(w - s.length) + s
s.padStart(w)
When to use
- Dividers and separator lines in console or log output
- Indentation by nesting depth
- Building a repeated pattern of known length
- Padding to a width → padStart or padEnd, which cannot throw
- The count may be negative → clamp, or use a pad method
- The count comes from user input → bound it first
- Joining a list with a separator → join
Notes
FAQ
Because there is no sensible answer — unlike a slice index, where "past the end" naturally clamps, a negative number of copies is simply meaningless. The specification chose an error over silently treating it as zero, which does catch genuine arithmetic bugs.
'x'.repeat(Math.max(0, n)); // the usual guard