How to Create a String by Repeating a Character in JavaScript
A common task in programming is to generate a string that consists of a character or substring repeated a specific number of times. This is useful for creating text-based dividers, padding strings to a certain length, or initializing strings for later use. Modern JavaScript provides a simple and highly readable method for this: String.prototype.repeat().
This guide will teach you how to use the modern repeat() method, explain the classic (but more complex) Array.join() trick, and show why repeat() is the superior choice for this task.
The Modern Method (Recommended): String.prototype.repeat()
The string.repeat() method is the standard, built-in tool for this job. It constructs and returns a new string containing the specified number of copies of the string on which it was called.
For example, you need to create a string that consists of the character 'a' repeated 5 times.
This single, readable line is all you need.
const character = 'a';
const times = 5;
const repeatedString = character.repeat(times);
console.log(repeatedString); // Output: "aaaaa"
// It also works with longer substrings
const multiCharRepeat = 'abc-'.repeat(3);
console.log(multiCharRepeat); // Output: "abc-abc-abc-"
This is the most concise and idiomatic way to perform this operation.
The Classic Method: The Array.join() Trick
Before repeat() was introduced, a common workaround was to use the Array constructor and the .join() method. This method is less intuitive but is useful to recognize in older codebases.
The logic:
- Create a new array of length
N + 1. This array will be sparse (full of empty slots). - Call the
.join()method on this array, using the character you want to repeat as the separator.
Solution:
const character = 'a';
const times = 5;
// Create an array with `times + 1` empty slots.
const tempArray = Array(times + 1);
// Join the empty slots with the character.
const repeatedString = tempArray.join(character);
console.log(repeatedString); // Output: "aaaaa"
How it works:
- An array of
N + 1elements hasN"gaps" between its elements. - The
join()method fills these gaps with the separator string, effectively creatingNcopies of your character.
Why repeat() is the Best Practice
While both methods achieve the same result, the repeat() method is superior for several reasons:
- Readability: The code
char.repeat(5)is self-documenting. Its purpose is immediately clear. TheArray(6).join(char)trick is clever but obscure and requires a moment of thought to understand. - Conciseness: It's a single, direct method call that doesn't require the
N + 1mental calculation. - Performance: Native string methods like
repeat()are generally highly optimized by the JavaScript engine and are typically faster than array-based workarounds.
For these reasons, you should always prefer repeat() in modern JavaScript code.
Practical Example: Creating a Text Divider
A perfect use case for repeat() is to generate a divider for formatting console output or creating a horizontal rule in a text-based UI.
function logWithDivider(message) {
const divider = '-'.repeat(40);
console.log(divider);
console.log(message);
console.log(divider);
}
// Example Usage:
logWithDivider('System Report');
Output:
----------------------------------------
System Report
----------------------------------------
Conclusion
For creating a string by repeating a character or substring, the String.prototype.repeat() method is the definitive best practice.
- The syntax is clean, direct, and readable:
'char'.repeat(N). - It is the most performant and idiomatic solution in modern JavaScript.
- While the
Array(N + 1).join('char')trick works, it is an outdated pattern that is less clear and should be avoided in new code.