CodeZettaInterview Hub

JavaScript · DOM · Mid-Level · Debugging

What is the difference between reflow (layout) and repaint, and how can JS trigger them inefficiently?

Short Interview Answer

Reflow recalculates geometry; repaint updates pixels without necessarily reflowing. Reading layout then writing styles in loops causes thrashing.

Detailed Explanation

Changing geometry-affecting properties (width, height, top, font sizes) can invalidate layout. Color/visibility changes may repaint without full layout. A common anti-pattern: alternate `offsetHeight` reads with style writes in a loop, forcing synchronous reflow each iteration. Batch reads then writes, use `transform`/`opacity` for animations where possible (compositor-friendly), and prefer class toggles over many inline styles. Virtualization reduces DOM size, cutting layout costs.

Example

// thrashing
for (const el of els) {
  const h = el.offsetHeight; // forces layout
  el.style.height = h + 10 + 'px'; // invalidates
}

Interview Tip

Name layout thrashing explicitly.

Common Mistake

Animating `top/left` instead of `transform` without discussing cost.

Did you know this answer?