JavaScript
Programming
Web Development
Coding Tutorials
String Manipulation

Repeat a string in JavaScript a number of times

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In modern JavaScript, the normal way to repeat a string is String.prototype.repeat. It is short, readable, and built into the language, but it is still worth understanding how it treats invalid counts and when a fallback loop might be needed for older environments or special constraints.

The Standard Solution: repeat

javascript
1const text = "ab";
2const result = text.repeat(4);
3
4console.log(result); // abababab

That is the primary answer for current JavaScript.

repeat expects a non-negative count. It will:

  • return an empty string for 0
  • truncate decimals toward zero
  • throw a RangeError for negative or infinite counts
javascript
console.log("x".repeat(0));    // ""
console.log("x".repeat(3.9));  // "xxx"

Wrapping It Safely

If the count comes from user input or another external source, validate it before repeating.

javascript
1function repeatText(text, count, maxLength = 1000000) {
2  if (typeof text !== "string") {
3    throw new TypeError("text must be a string");
4  }
5
6  if (!Number.isFinite(count) || count < 0) {
7    throw new RangeError("count must be a finite non-negative number");
8  }
9
10  const times = Math.trunc(count);
11  if (text.length * times > maxLength) {
12    throw new RangeError("result would be too large");
13  }
14
15  return text.repeat(times);
16}
17
18console.log(repeatText("-=", 5));

This protects code from accidental huge allocations.

Fallback for Older Environments

If you are stuck on an environment without repeat, a simple loop works:

javascript
1function repeatFallback(text, count) {
2  if (count <= 0) return "";
3
4  let result = "";
5  for (let i = 0; i < count; i++) {
6    result += text;
7  }
8  return result;
9}
10
11console.log(repeatFallback("na", 4)); // nananana

This is fine for small counts, though the built-in method is usually preferable when available.

Repetition Versus Padding

Sometimes developers repeat a string when the real goal is padding. For padding, dedicated methods communicate intent more clearly.

javascript
const id = "42";
console.log(id.padStart(6, "0")); // 000042

Use repetition when you want repeated content. Use padding methods when you want formatting width.

Older Manual Approaches

Before repeat became widely available, developers often used loops:

javascript
1function repeatFallback(text, count) {
2  let result = "";
3  for (let i = 0; i < count; i++) {
4    result += text;
5  }
6  return result;
7}

That still works, but the native method is usually clearer and often better optimized in current engines.

For normal application code, built-in APIs are usually the strongest default unless compatibility requirements force a fallback for legacy runtimes or embedded environments later on in maintenance work.

Real-World Uses

String repetition shows up in:

  • separators in logs or reports
  • test-data generation
  • indentation helpers
  • templating and text-based protocols

Because it is so small, people often skip validation and later discover performance or memory issues when counts are not controlled.

Common Pitfalls

One common mistake is assuming negative counts will quietly produce an empty string. They do not; repeat throws.

Another issue is repeating untrusted input without a limit. Very large outputs can waste memory or block the UI thread.

A third pitfall is using manual loops everywhere in modern codebases where repeat is simpler and more expressive.

Summary

  • Use String.prototype.repeat as the standard way to repeat strings in JavaScript.
  • Validate counts when they come from external input.
  • Use a fallback loop only when compatibility really requires it.
  • Prefer padStart or padEnd when the real problem is formatting, not repetition.
  • Keep an eye on output size so repetition does not become a memory problem.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.