String.prototype.repeat()

Returns a new string containing a given number of copies of the original string.

Signature
repeat(count)
  • Added in JavaScript ES2015

Parameters

ParameterTypeDescription
$countnumberAn integer between 0 and +Infinity indicating how many times to repeat the string. Fractional values are truncated toward zero.

Return value

stringA new string containing the specified number of copies of the original string, concatenated together.

Errors

Throws a RangeError if count is negative, is Infinity, or if the resulting string would exceed the engine's maximum string length.

repeat() concatenates a string with itself count times and hands back the result. It is the direct replacement for the old new Array(n + 1).join(str) trick, and it is both clearer and faster.

When to reach for it

Reach for it whenever a fixed run of characters is needed: horizontal rules in console output, indentation for a pretty-printer, ASCII bar charts, masking the middle of an account number, or padding a value out with a known filler when you want the repetition count rather than the final width.

What trips people up

The count is truncated, not rounded: "ab".repeat(2.9) gives "abab". Zero is legal and returns an empty string, which is often the correct behaviour for an empty-state divider. Negative values and Infinity both throw a RangeError, so any count derived from arithmetic — a width minus a label length, for instance — must be clamped with Math.max(0, n) before it reaches repeat().

Memory is the other limit. Engines cap string length in the hundreds of millions of code units; a repeat that crosses it throws RangeError rather than degrading gracefully.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Draw a divider line the width of a console table
  • Indent nested output by depth in a recursive pretty-printer
  • Render a quick ASCII bar chart from numeric values
  • Mask all but the last four digits of a card number

Frequently asked questions

How do I repeat a string n times in JavaScript?

Call str.repeat(n) — for example "ab".repeat(3) returns "ababab". It replaces the older Array(n + 1).join(str) idiom and is available in every current engine since ES2015.

Why does repeat throw a RangeError?

repeat throws RangeError when the count is negative, is Infinity, or when the resulting string would exceed the engine's maximum string length. Counts computed from a subtraction are the usual culprit; clamp them with Math.max(0, count).

Does repeat modify the original string?

No. JavaScript strings are immutable, so repeat returns a brand-new string and leaves the original variable pointing at the unchanged value.

More examples

Counts are truncated, and bad counts throw

A count of 0 produces the empty string. 3.9 is truncated toward zero to 3, so the string appears three times rather than four. A negative count is not clamped — it raises a RangeError, which is why counts computed by subtraction need guarding.

Example · javascript
console.log("abc".repeat(0) === "");
console.log("abc".repeat(2));
console.log("abc".repeat(3.9));

try {
  "abc".repeat(-1);
} catch (err) {
  console.log(err.name);
}

Indenting a nested structure

Each recursion level multiplies a two-space unit by the current depth, producing consistent indentation without tracking a running prefix string. At depth 0 the repeat yields an empty string, so the root line starts flush left.

Example · javascript
const tree = { app: { src: { "index.js": null }, "README.md": null } };

function print(node, depth = 0) {
  for (const [key, child] of Object.entries(node)) {
    console.log("  ".repeat(depth) + key);
    if (child) print(child, depth + 1);
  }
}

print(tree);

Discussion

  • Be the first to comment on this lesson.