repeat()
ES6+Returns a new string with a specified number of copies of the string.
Syntax
string.repeat(count)Parameters
count number Number of times to repeat the string
Return Value
A new string containing the specified number of copies
Examples
const str = 'abc';
console.log(str.repeat(3));
console.log('='.repeat(10)); 📌 When to Use
Use repeat() for creating repeated patterns like separators, indentation, placeholder text, or any situation where you need a string duplicated a specific number of times.
⚠️ Common Mistakes
Using a negative count or Infinity, which throws a RangeError. Always validate the count before calling repeat().
Forgetting that repeat(0) returns an empty string, not the original string.
Using repeat() with very large numbers without considering memory limits - it can cause browser crashes.
✅ Best Practices
Validate the count parameter is a non-negative integer before calling repeat() to avoid RangeError.
Use repeat() for creating visual separators in console output: console.log("=".repeat(50)).
Combine with slice() for fixed-width string generation: ("0".repeat(5) + num).slice(-5) for zero-padding.
⚡ Performance Notes
repeat() is highly optimized in modern engines using doubling algorithms. It is much faster than loop-based concatenation for creating repeated strings. However, be mindful of memory when repeating strings many times - the result string must fit in memory.
🌍 Real World Example
Text Formatting and Visual Elements
repeat() is commonly used for creating text-based visual elements, generating indentation, creating loading indicators, and formatting output for display.
// Create a visual separator for console output
function printSection(title) {
const width = 50;
const separator = '='.repeat(width);
const padding = ' '.repeat(Math.floor((width - title.length) / 2));
console.log(separator);
console.log(padding + title);
console.log(separator);
}
printSection('Report');
// ==================================================
// Report
// ==================================================
// Generate tree-like indentation for nested structures
function printTree(node, depth = 0) {
const indent = ' '.repeat(depth);
const prefix = depth > 0 ? indent + '├─ ' : '';
console.log(prefix + node.name);
if (node.children) {
node.children.forEach(child => printTree(child, depth + 1));
}
}
// Create a simple text progress bar
function progressBar(percent, width = 30) {
const filled = Math.round(width * percent / 100);
const empty = width - filled;
return '[' + '█'.repeat(filled) + '░'.repeat(empty) + '] ' + percent + '%';
}
console.log(progressBar(75)); // [██████████████████████░░░░░░░░] 75%
// Generate placeholder text
function generateLorem(words) {
const lorem = 'Lorem ipsum dolor sit amet ';
return lorem.repeat(Math.ceil(words / 5)).split(' ').slice(0, words).join(' ');
}
console.log(generateLorem(10));