Repeat

Master CSS Grid repeat() and JavaScript String.repeat() for efficient, maintainable web development with practical code examples.

What is Repeat in Web Development?

The repeat concept appears in two critical areas of modern web development: CSS Grid layout and JavaScript string manipulation. Both leverage the same fundamental idea--efficiently creating multiple copies of something without writing repetitive code. This approach reduces errors, improves maintainability, and makes your codebase cleaner and easier to understand.

When you find yourself writing the same value multiple times in succession, the repeat function or method provides an elegant solution. Instead of manually listing each occurrence, you specify the count and the value once, letting the browser or JavaScript engine handle the repetition. This becomes especially valuable as projects scale--where manual repetition would become tedious and error-prone.

This guide covers:

  • CSS Grid repeat() function with fr units
  • JavaScript String.repeat() method
  • Practical code examples for both
  • Common use cases and patterns
  • Best practices for each implementation

Whether you're building complex grid layouts or generating formatted strings, mastering the repeat concept will make your code more concise and maintainable.

CSS Grid repeat() Function

The CSS repeat() function represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form. This function is exclusively used with CSS Grid properties grid-template-columns and grid-template-rows, as documented in the MDN Web Docs on CSS repeat().

Before and After repeat()

/* Without repeat - verbose and error-prone */
grid-template-columns: 200px 200px 200px 200px 200px;

/* With repeat - clean and maintainable */
grid-template-columns: repeat(5, 200px);

The repeat() function dramatically simplifies grid definitions, especially when working with responsive designs that require consistent column or row patterns.

Syntax and Parameters

The repeat() function accepts two arguments: the repeat count and the track size(s) to repeat.

/* Basic syntax */
repeat(count, track-size)

/* Examples */
repeat(4, 1fr) /* 4 equal fractional columns */
repeat(3, 200px) /* 3 columns of 200px each */
repeat(2, 1fr 2fr) /* 2 repetitions of pattern: 1fr 2fr */

The first parameter specifies how many times to repeat, while the second parameter defines the track size. You can even repeat multiple track sizes at once by providing a space-separated list, making complex grid patterns easy to define.

Complex Patterns with Named Lines

You can combine repeat() with named grid lines for more sophisticated layouts:

/* Named lines within repeat */
grid-template-columns: repeat(4, [col-start] 1fr [col-end]);

This creates repeated named lines: col-start, col-end, col-start, col-end, and so on. Named lines help with item placement using the grid-column and grid-row properties.

The fr Unit Explained

The fr unit (short for "fraction") is a CSS Grid-specific unit that represents a fraction of the available space in the grid container, as explained in the DigitalOcean guide on the fr unit. When combined with repeat(), the fr unit creates powerful responsive layouts that adapt fluidly to container size.

/* 3 equal columns that share available space */
grid-template-columns: repeat(3, 1fr);

/* First column gets 1 part, others get 2 parts each */
grid-template-columns: 1fr repeat(2, 2fr);

/* Mixed fixed and fractional */
grid-template-columns: 200px repeat(3, 1fr);

How fr Units Allocate Space

Each fr unit allocates space proportionally. The browser calculates the total "parts" and distributes available space accordingly:

Track PatternDistributionVisual Result
repeat(3, 1fr)3 equal partsThree equal-width columns
1fr 2fr 1fr1:2:1 ratioMiddle column is twice as wide
2fr 1fr2:1 ratioFirst column twice as wide as second
200px repeat(3, 1fr)Fixed + 3 equal partsSidebar + three equal content columns

The fr unit is particularly powerful because it respects minimum and maximum sizes when combined with minmax(), enabling truly fluid responsive layouts without media queries.

Auto-Fill and Auto-Fit Keywords

Two keyword values make repeat() exceptionally powerful for responsive design: auto-fill and auto-fit, as covered in the MDN Web Docs on CSS repeat(). These keywords allow grids to automatically adjust the number of tracks based on available container space.

/* auto-fill: creates as many columns as fit, leaving empty space */
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));

/* auto-fit: similar but collapses empty tracks */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));

Key Differences

The difference becomes apparent when there are fewer items than can fill the container:

Scenarioauto-fill Behaviorauto-fit Behavior
4 items, container fits 6 columns6 column slots with 2 empty4 stretched columns filling space
2 items, container fits 6 columns6 column slots with 4 empty2 stretched columns filling space
Responsive resizeColumns adjust but slots remainColumns grow/shrink to fill space

auto-fill: Creates as many columns as can fit in the container while leaving empty space for potential content. The column slots remain available even if empty.

auto-fit: Similar to auto-fill but collapses empty tracks and stretches the remaining columns to fill the available space, creating a more polished look when you have fewer items than column slots.

JavaScript String.repeat() Method

The JavaScript String.prototype.repeat() method constructs and returns a new string containing the specified number of copies of the string it was called on, concatenated together. This method has been part of ECMAScript 2015 (ES6) and is widely supported across all modern browsers.

"hello".repeat(3); // "hellohellohello"
"abc".repeat(2); // "abcabc"

Syntax

string.repeat(count)

Parameters

The count parameter must be an integer between 0 and Infinity (inclusive), indicating the number of times to repeat the string. A negative value or non-integer will result in a RangeError.

Return Value

The method returns a new string containing the specified number of copies concatenated together. The original string remains unchanged.

"abc".repeat(0); // "" (empty string)
"abc".repeat(1); // "abc"
"abc".repeat(2); // "abcabc"

Exceptions

A RangeError is thrown in these cases:

  • count is negative
  • count exceeds the maximum string length (varies by JavaScript engine)
  • count is Infinity or NaN
"abc".repeat(-1); // RangeError: Invalid count value
"abc".repeat(Infinity); // RangeError: Invalid count value
"abc".repeat(1/0); // RangeError: Invalid count value

Generic Behavior

The repeat() method is generic and works with any object that has a toString() method returning a string value, making it flexible beyond simple string usage.

Practical JavaScript repeat() Examples

Creating Separator Lines

const line = "-".repeat(40);
console.log(line);
// "----------------------------------------"

Indentation

const indent = " ".repeat(4);
console.log(indent + "Indented text");
// " Indented text"

Star Rating Generator

function createStarRating(rating) {
 return "★".repeat(rating) + "☆".repeat(5 - rating);
}
createStarRating(4); // "★★★★☆"

String Padding

function padLeft(str, length, char = " ") {
 return char.repeat(Math.max(0, length - str.length)) + str;
}
padLeft("42", 5, "0"); // "00042"

Generating Test Data

function generateTestItems(count) {
 return Array(count).fill(null).map((_, i) =>
 `Item ${i + 1}: ${"-".repeat(i + 1)}`
 );
}
// Output: ["Item 1: -", "Item 2: --", "Item 3: ---", ...]

Progress Bar Visualization

function renderProgressBar(percent, length = 20) {
 const filled = "█".repeat(Math.round(length * percent / 100));
 const empty = "░".repeat(length - filled.length);
 return `[${filled}${empty}] ${percent}%`;
}
renderProgressBar(75); // "[████████████████████░░] 75%"

Safe Usage with Validation

function safeRepeat(str, count) {
 if (count < 0 || !Number.isFinite(count)) {
 return ""; // or throw an error
 }
 return str.repeat(Math.floor(count));
}

CSS Grid Layout Patterns

Card Grid with Consistent Spacing

The classic card gallery pattern becomes trivial with repeat(auto-fill, minmax()). Cards automatically wrap and resize based on available space.

.gallery {
 display: grid;
 grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
 gap: 1.5rem;
}
/* Cards: minimum 250px, but stretch to fill available space */

Dashboard Layout

Complex dashboard layouts often use a 12-column grid for flexible widget placement.

.dashboard {
 display: grid;
 grid-template-columns: repeat(12, 1fr);
 grid-template-rows: repeat(2, 150px);
 gap: 1rem;
}
/* Widgets can span 1-12 columns as needed */

Holy Grail Layout

The classic "Holy Grail" layout (header, footer, sidebar, main content) is elegantly achieved with CSS Grid.

.holy-grail {
 display: grid;
 grid-template-columns: 200px 1fr 200px;
 grid-template-rows: auto 1fr auto;
 min-height: 100vh;
}
/* Header, main content area, footer with two sidebars */

Responsive Photo Gallery

.photo-gallery {
 display: grid;
 grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
 gap: 0.5rem;
}
/* Photos automatically arrange and stretch */

These patterns demonstrate how repeat() combined with fr units and the minmax() function creates layouts that would require extensive media queries with traditional CSS. To learn more about modern CSS layout techniques, explore our CSS Grid Layout guide.

Best Practices

CSS repeat() Best Practices

  1. Use minmax() with auto-fill/auto-fit for truly responsive grids without media queries. This combination automatically adjusts column counts based on container width.

  2. Combine with fr units for proportional layouts that adapt to container size. The fr unit ensures columns share space intelligently.

  3. Avoid hardcoded pixel values when possible--use relative units for flexibility. Combining repeat() with min-content, max-content, and auto provides more robust layouts.

  4. Consider content size with min-content and max-content keywords to prevent content from overflowing or leaving excessive whitespace.

  5. Set appropriate minmax() values--too small and items become squished; too large and you lose the responsive benefits.

JavaScript repeat() Best Practices

  1. Validate count before calling to avoid RangeError in edge cases. Always check for negative values and ensure count is a finite integer.

  2. Use for visual/formatting purposes where string repetition serves a genuine purpose--separator lines, indentation, padding, and visual indicators.

  3. Consider performance for very large counts. Strings have maximum length limits that vary by engine, and extremely long strings can impact memory.

  4. Remember it returns a new string--the original remains unchanged. This is important for immutability and understanding memory implications.

Common Mistakes to Avoid

CSS Mistakes:

  • Forgetting minmax() with auto-fill/auto-fit, leading to infinite columns
  • Setting minmax() minimums too small, causing content to overflow
  • Mixing fr with fixed units without understanding how proportions calculate

JavaScript Mistakes:

  • Passing negative counts without validation
  • Assuming repeat(0) returns the original string (it returns empty string)
  • Forgetting that very large counts can throw RangeError

By following these best practices, you'll create more maintainable and robust code that handles edge cases gracefully.

Browser Compatibility

Both CSS repeat() and JavaScript String.repeat() are widely supported across modern browsers:

JavaScript String.repeat()

BrowserVersionRelease Date
Chrome41+March 2015
Firefox34+November 2014
Safari9+September 2015
Edge12+July 2015
Opera28+March 2015

CSS Grid repeat()

BrowserVersionRelease Date
Chrome57+March 2017
Firefox52+March 2017
Safari10.1+March 2017
Edge16+October 2017
Opera44+March 2017

The JavaScript repeat() method has been available since September 2015 in ES6, making it one of the longer-established modern JavaScript features. CSS Grid and its repeat() function reached full support in all major browsers by mid-2017.

For legacy browser support (Internet Explorer), consider providing fallbacks using @supports feature detection. Most modern web applications can safely use these features without polyfills, as global support exceeds 97% worldwide.

Feature Detection

/* Example: providing fallback for older browsers */
@supports (display: grid) {
 .grid-container {
 display: grid;
 grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
 }
}

For projects requiring support for older browsers, you can use Can I Use to check current market share of specific browser versions in your target regions.

Summary

The repeat concept serves as an essential tool in both CSS and JavaScript, enabling efficient creation of repetitive structures without verbose code duplication.

CSS Grid repeat() with fr units creates responsive layouts with minimal code. Combined with auto-fill, auto-fit, and minmax(), it eliminates the need for extensive media queries and creates fluid layouts that adapt to any screen size.

JavaScript String.repeat() provides a clean way to generate repeated strings for formatting, testing, and display purposes. From creating separator lines to generating star ratings, this method simplifies common string manipulation tasks.

Mastering both implementations will significantly improve your web development workflow by reducing repetitive code and making your projects more maintainable. These concepts form the foundation of modern, efficient web development practices.

Ready to build on this knowledge? Explore our comprehensive web development services to learn how we can help you create efficient, maintainable websites and applications. For more CSS layout techniques, check out our guide on CSS Grid Layout and Box Model fundamentals.

Frequently Asked Questions