Skip to content

String.prototype.repeat(): repeat text n times (ES2015)

  • What String.prototype.repeat() returns and how it converts its count.
  • 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() or padEnd() is a better fit.

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).

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('-')); // -----
// ES2015
console.log('-'.repeat(5)); // -----
console.log('ab'.repeat(3)); // ababab
console.log('ab'.repeat(0)); // (empty string)
// Fragment: signature
str.repeat(count)

The specification’s steps:

  1. Convert this to a string (null or undefined throws a TypeError).
  2. Convert count with ToIntegerOrInfinity: numbers are truncated toward zero, strings are parsed, and NaN becomes 0.
  3. If the result is negative or Infinity, throw a RangeError.
  4. If it is 0, return "". Otherwise return count copies 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 truncated
console.log(JSON.stringify('ab'.repeat('3'))); // "ababab": strings are converted
console.log(JSON.stringify('ab'.repeat(NaN))); // "": NaN becomes 0
console.log(JSON.stringify('ab'.repeat(-0.5))); // "": -0.5 truncates to 0
console.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: -1
Infinity -> RangeError - Invalid count value: Infinity
1073741824 -> RangeError - Invalid string length

Note 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.

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.00
Coffee beans 1 kg 18.50
A very long product name tha... 9.99
------------------------------------
Total 52.49
====================================
Mon ###############..... 42
Tue #################### 57
Wed ######.............. 18

Without 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.

  • Negative computed counts. ' '.repeat(width - text.length) throws as soon as the text is wider than the column. Clamp with Math.max(0, n) or truncate the text, as row does.
  • Using repeat for alignment. To pad a value to a width, padStart() and padEnd() state the intent, compute the gap for you, and handle the “already too long” case.
  • Counting characters as columns. repeat and length count UTF-16 code units: '📦'.length is 2, so '📦'.repeat(3).length is 6. Emoji and East Asian wide characters also take two terminal columns. Fixed-width layouts only line up for ASCII text.
  • Huge results. repeat builds the whole string in memory. A count derived from user input can hit the engine’s maximum string length (a RangeError) or exhaust memory well before it. Validate the count.
  • Expecting an array. 'x'.repeat(3) is a string. For an array of repeated values use Array(3).fill('x') or Array.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 6

Output:

Orders
Open
ORD-1042
Shipped
2 6
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)

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.

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.

  • repeat (ES2015) returns count copies of a string; the count is truncated, and NaN or 0 gives "".
  • Negative and infinite counts throw RangeError, and so does exceeding the engine’s maximum string length.
  • Guard computed counts, and prefer padStart/padEnd for alignment.
  • Lengths are UTF-16 code units, so text layouts only line up for narrow characters.