# What are the key requirements when iterating over lists of data in LWC templates?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, List Rendering, For Each

Read it on the site: https://www.forcechallenges.com/interview-questions/what-are-the-key-requirements-when-iterating-over-lists-of-data-in-lwc-templates

## Answer

**Basics:** Templates cannot run loops in JavaScript expressions, so you declare iteration in markup. Each rendered item needs a key so the engine can match old and new items during re-render, moving or updating only what changed.

**How it works:**
1. The data property must be an array (or iterable).
2. Write `<template for:each={contacts} for:item="c">` and, directly on the first child element, `key={c.Id}`.
3. Inside the loop use `{c.Name}`. `for:index="i"` exposes the index.
4. Alternative: `iterator:it={contacts}` gives `it.value`, `it.index`, `it.first`, `it.last`, handy for separators or headers.
5. Template expressions are limited to property access, so compute derived values in JavaScript.

**Advanced / deep dive:** Keys let the diff algorithm preserve DOM elements and component instances when the list is reordered, inserted or removed. Using the index as key makes reordering destroy and recreate state (input values, child components). Keys must be unique among siblings in the loop, not globally. Because you cannot call functions or use ternaries in the template, precompute per-row values (such as a CSS class) while mapping the array. Wire data is frozen, so map to a new array rather than mutating. For large lists (thousands of rows) render a page at a time, use `lightning-datatable` with infinite loading, or virtualize; each rendered element has a cost. Nested loops are allowed; each level needs its own key. Empty arrays render nothing, so pair with `lwc:if` to show an empty state.

**Code / config example:**
```html
<template lwc:if={hasContacts}>
    <ul>
        <template for:each={rows} for:item="r">
            <li key={r.Id} class={r.cssClass}>{r.Name}</li>
        </template>
    </ul>
</template>
<template lwc:else><p>No contacts.</p></template>
```
```javascript
get hasContacts() { return this.rows.length > 0; }
// map once, precomputing derived values
this.rows = data.map(c => ({ ...c, cssClass: c.Active__c ? 'slds-item active' : 'slds-item' }));
```

**Hidden gotchas & must-remember points:**
- `key` goes on the first element inside the loop, not on the `<template>` tag itself.
- Index keys cause bugs with reordering and stateful inputs.
- Keys must be strings or numbers; objects will not work.
- You cannot write `{r.Amount > 100}` or call methods in templates; use a getter or precomputed field.
- The array must be actual array data; plain objects are not iterable by `for:each`.
- `for:index` starts at 0.

**Best practice:** Use a stable record Id as key and precompute display fields when you map the data.

---
Source: ForceChallenges · last updated 2026-11-02
