String.prototype.repeat(): repeat text n times (ES2015)
What you’ll learn
Section titled “What you’ll learn”- What
String.prototype.repeat()returns and how it converts itscount. - When it throws a
RangeError, including the engine’s maximum string length. - How to use it for separators, indentation and text bar charts without negative-count crashes.
- When
padStart()orpadEnd()is a better fit.
Summary
Section titled “Summary”TL;DR: str.repeat(count) returns a new string made of count copies of str. count is converted to an integer (truncating fractions); 0 gives "", and a negative or infinite count throws a RangeError.
It was added in ECMAScript 2015 (ES6) and works in every current browser and server runtime (see Compatibility).
The problem it solves
Section titled “The problem it solves”Before ES2015, repeating text meant a loop or the Array.join trick, which creates an array of n + 1 empty slots and joins them with the text as the separator. It works, but the off-by-one is easy to miss.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.
// Before ES2015: build an array of n + 1 holes and join them.console.log(new Array(5 + 1).join('-')); // -----
// ES2015console.log('-'.repeat(5)); // -----console.log('ab'.repeat(3)); // abababconsole.log('ab'.repeat(0)); // (empty string)How it works
Section titled “How it works”// Fragment: signaturestr.repeat(count)The specification’s steps:
- Convert
thisto a string (nullorundefinedthrows aTypeError). - Convert
countwithToIntegerOrInfinity: numbers are truncated toward zero, strings are parsed, andNaNbecomes0. - If the result is negative or
Infinity, throw aRangeError. - If it is
0, return"". Otherwise returncountcopies concatenated.
The spec allows strings up to 253 − 1 code units, but engines set much lower limits. In Node.js 22 (V8) the limit is 536,870,888 code units (require('node:buffer').constants.MAX_STRING_LENGTH), and a result above it throws a RangeError too.
console.log(JSON.stringify('ab'.repeat(2.9))); // "abab": the count is truncatedconsole.log(JSON.stringify('ab'.repeat('3'))); // "ababab": strings are convertedconsole.log(JSON.stringify('ab'.repeat(NaN))); // "": NaN becomes 0console.log(JSON.stringify('ab'.repeat(-0.5))); // "": -0.5 truncates to 0console.log(JSON.stringify(''.repeat(1e9))); // "": the empty string is cheap to repeat
for (const count of [-1, Infinity, 2 ** 30]) { try { 'ab'.repeat(count); } catch (error) { console.log(count, '->', error.constructor.name, '-', error.message); }}Output:
"abab""ababab"""""""-1 -> RangeError - Invalid count value: -1Infinity -> RangeError - Invalid count value: Infinity1073741824 -> RangeError - Invalid string lengthNote that -0.5 does not throw: the spec truncates it to the mathematical value 0, which is not negative. The messages are V8’s wording; other engines word them differently, and their maximum lengths can differ.
Realistic example
Section titled “Realistic example”OrdersPortal sends a plain-text order summary in emails and writes a daily volume chart to its logs. repeat draws the rules and bars; the row helper computes the gap and truncates long names so the count can never go negative:
// receipt.mjs - plain-text order summary for OrdersPortal emails and logs.const WIDTH = 36;
function line(char = '-') { return char.repeat(WIDTH);}
function row(label, amount) { const price = amount.toFixed(2); const room = WIDTH - price.length - 1; // keep at least one space before the price const text = label.length > room ? `${label.slice(0, room - 3)}...` : label; return text + ' '.repeat(WIDTH - text.length - price.length) + price;}
function bar(value, max, width = 20) { const filled = Math.round((value / max) * width); return '#'.repeat(filled) + '.'.repeat(width - filled);}
const order = { id: 'ORD-1042', items: [ { name: 'Ceramic mug x2', total: 24 }, { name: 'Coffee beans 1 kg', total: 18.5 }, { name: 'A very long product name that overflows', total: 9.99 }, ],};
console.log(line('='));console.log(`Order ${order.id}`);console.log(line());for (const item of order.items) console.log(row(item.name, item.total));console.log(line());console.log(row('Total', order.items.reduce((sum, i) => sum + i.total, 0)));console.log(line('='));
const ordersPerDay = { Mon: 42, Tue: 57, Wed: 18 };const max = Math.max(...Object.values(ordersPerDay));for (const [day, count] of Object.entries(ordersPerDay)) { console.log(`${day} ${bar(count, max)} ${count}`);}Output:
====================================Order ORD-1042------------------------------------Ceramic mug x2 24.00Coffee beans 1 kg 18.50A very long product name tha... 9.99------------------------------------Total 52.49====================================Mon ###############..... 42Tue #################### 57Wed ######.............. 18Without the truncation, the long product name would make WIDTH - text.length - price.length negative and repeat would throw RangeError: Invalid count value. The row function could also be written as text.padEnd(WIDTH - price.length) + price; padEnd never throws for a short target length, it simply returns the string unchanged.
Common mistakes
Section titled “Common mistakes”- Negative computed counts.
' '.repeat(width - text.length)throws as soon as the text is wider than the column. Clamp withMath.max(0, n)or truncate the text, asrowdoes. - Using
repeatfor alignment. To pad a value to a width,padStart()andpadEnd()state the intent, compute the gap for you, and handle the “already too long” case. - Counting characters as columns.
repeatandlengthcount UTF-16 code units:'📦'.lengthis2, so'📦'.repeat(3).lengthis6. Emoji and East Asian wide characters also take two terminal columns. Fixed-width layouts only line up for ASCII text. - Huge results.
repeatbuilds the whole string in memory. A count derived from user input can hit the engine’s maximum string length (aRangeError) or exhaust memory well before it. Validate the count. - Expecting an array.
'x'.repeat(3)is a string. For an array of repeated values useArray(3).fill('x')orArray.from({ length: 3 }, () => ({}))for distinct objects.
A short indentation helper shows the typical safe use:
// Indentation for a nested outline: depth * 2 spaces.const indent = (depth) => ' '.repeat(depth);const tree = [['Orders', 0], ['Open', 1], ['ORD-1042', 2], ['Shipped', 1]];for (const [label, depth] of tree) console.log(indent(depth) + label);
// repeat counts UTF-16 code units, not what users see.console.log('📦'.length, '📦'.repeat(3).length); // 2 6Output:
Orders Open ORD-1042 Shipped2 6When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
A separator, rule or bar of n characters |
char.repeat(n) |
| Indentation by depth | ' '.repeat(depth) |
| Pad a value to a fixed width | padStart() / padEnd() |
An array of n copies |
Array(n).fill(value) |
| Indentation in JSON output | JSON.stringify(value, null, 2) |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, String.prototype.repeat is supported in Chrome 41, Edge 12, Firefox 24, Safari 9 (including iOS), Opera 28, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it; core-js provides a polyfill.
TypeScript: declared in lib.es2015.core.d.ts as repeat(count: number): string, so a string count such as '3' is a type error even though JavaScript accepts it.
Interview questions
Section titled “Interview questions”1. What do 'ab'.repeat(2.9), 'ab'.repeat(-1) and 'ab'.repeat(-0.5) return?
"abab", a RangeError, and "". The count is truncated toward zero; only a result below zero (or Infinity) throws, and -0.5 truncates to 0.
2. How did you repeat a string before ES2015?
With new Array(n + 1).join(str): an array of n + 1 empty slots joined with str as the separator gives n copies. A loop with += also works.
3. Senior scenario: OrdersPortal’s plain-text report endpoint lets users choose an “indent depth” and builds lines with ' '.repeat(depth). What can go wrong and how do you harden it?
A large or non-numeric depth from the request can throw a RangeError (negative, Infinity, over the maximum string length) or allocate hundreds of megabytes per line, which is a cheap denial-of-service. Parse the value as an integer, enforce a small range (for example 0 to 8) at the API boundary, return a 400 for anything else, and cap total output size. Wrap generation in error handling so a RangeError becomes a clear client error rather than a 500.
Key takeaways
Section titled “Key takeaways”repeat(ES2015) returnscountcopies of a string; the count is truncated, andNaNor0gives"".- Negative and infinite counts throw
RangeError, and so does exceeding the engine’s maximum string length. - Guard computed counts, and prefer
padStart/padEndfor alignment. - Lengths are UTF-16 code units, so text layouts only line up for narrow characters.
Related pages
Section titled “Related pages”- String.prototype.padStart() and String.prototype.padEnd(): pad to a target width.
- Template literals: build multi-line text.
- Unicode support: code units, code points and why
lengthsurprises. - Strings: string basics.
- JavaScript interview questions