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.
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
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
RangeErrorfor negative or infinite counts
Wrapping It Safely
If the count comes from user input or another external source, validate it before repeating.
This protects code from accidental huge allocations.
Fallback for Older Environments
If you are stuck on an environment without repeat, a simple loop works:
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.
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:
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.repeatas 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
padStartorpadEndwhen the real problem is formatting, not repetition. - Keep an eye on output size so repetition does not become a memory problem.
Related reading
- Repeatedly prompt user until resolved using nodeJS async-await
- Replace an image with Ajax on seaside
- Replace carets with HTML superscript markup using Java
- Retrying a failed async/promise function?
- Return multiple values in JavaScript?
- Return value from asynchronous OR synchronous JavaScript request
- Return value from nested callback instead of the parent function
- return value of a callback function in Node.js
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack 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.