intermediate
Layout
Calculate geometry from styles, content, fonts, viewport, constraints, and DOM changes that can force reflow.
Layout computes element geometry from style, content, fonts, viewport size, writing mode, and constraints. Some DOM reads such as offsetWidth or getBoundingClientRect can force pending style and layout work to finish synchronously. Performance answers should explain batching reads before writes and avoiding layout-dependent loops.
// Bad: interleaved read/write forces sync layout per item
for (const row of rows) {
row.style.height = row.offsetHeight + 10 + 'px';
}
// Better: read all, then write all
const heights = rows.map((row) => row.offsetHeight + 10);
rows.forEach((row, i) => { row.style.height = heights[i] + 'px'; });
requestAnimationFrame coalesces visual updates to the next frame but does not remove the cost of unnecessary layout.
On interviews: spot forced reflow and frame budget pressure in slow resize or scroll code.
Common pitfalls: a single forced layout can be acceptable; a read-write loop across many nodes is the real danger.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Batch reads, then batch writes.
- Avoid measuring inside tight loops.
- Use ResizeObserver instead of window resize spam.
- Profile layout in Performance panel.