Sub topic 7
Choosing between for:each and iterator
This chapter assumes you can write a basic LWC component, bind class properties with curly braces, and use lwc:if and lwc:else. It also assumes you have already rendered a list with for:each and know that each rendered item needs a key. The question here is which directive to pick when both can render your array.
What the two directives share
Both directives loop over an array and produce one block of markup per element. Their rules are the same in the places that matter:
- The loop is written on a
<template>tag, which adds nothing to the DOM. - The first real element inside that template needs a
keyattribute. - The key must be a string or a number and must be unique among the siblings in that loop.
- The key should come from the data, such as a record Id. It should not come from the position.
- Neither directive allows expressions in the template. Anything beyond reading a property must be computed in JavaScript.
Because of this, you can switch from one directive to the other without changing your data or your key. The choice depends only on what the template needs to know about each pass.
What each directive gives you
With for:each, you name the current element with for:item. You can also ask for its position with for:index.
<template for:each={contacts} for:item="contact" for:index="position">
<li key={contact.Id} data-position={position}>{contact.Name}</li>
</template>With iterator:name, you get one object per pass. You name that object yourself, and it has four properties:
| Property | Meaning |
|---|---|
| `value` | The current array element |
| `index` | The zero-based position |
| `first` | `true` for the first element only |
| `last` | `true` for the last element only |
<template iterator:it={contacts}>
<li key={it.value.Id}>{it.value.Name}</li>
</template>The difference is that iterator can tell you whether the current element is the first or the last. for:each has no equivalent, so it cannot do this directly.
A worked example: route stops
Suppose you show a route with a "Start" label on the first stop and a "Finish" label on the last stop. Here is the iterator version.
<!-- routeStops.html -->
<template>
<ol>
<template iterator:it={stops}>
<li key={it.value.id}>
<strong lwc:if={it.first}>Start: </strong>
<strong lwc:if={it.last}>Finish: </strong>
{it.value.name}
</li>
</template>
</ol>
</template>// routeStops.js
import { LightningElement } from 'lwc';
export default class RouteStops extends LightningElement {
stops = [
{ id: 's1', name: 'Central Station' },
{ id: 's2', name: 'Market Square' },
{ id: 's3', name: 'Harbor Gate' }
];
}The template reads it.first and it.last directly, and the JavaScript stays a plain array. This is the main case where iterator is the better fit.
The single-item edge case
When the array has exactly one element, it.first and it.last are both true on that pass. In the example above, a one-stop route would render "Start: Finish: Central Station". If that matters, decide which label wins. Handle it in JavaScript or add a guard in the template.
An empty array renders nothing, and no pass runs. That means a "Start" or "Finish" label can never appear without an item. An empty list still needs its own fallback message, which a later chapter covers.
Getting first and last with for:each
You can reproduce first and last with for:each by precomputing flags in JavaScript. The map callback receives the index and the whole array, so each element can carry its own flags.
// routeStops.js (for:each variant)
import { LightningElement } from 'lwc';
export default class RouteStops extends LightningElement {
rawStops = [
{ id: 's1', name: 'Central Station' },
{ id: 's2', name: 'Market Square' },
{ id: 's3', name: 'Harbor Gate' }
];
get stops() {
return this.rawStops.map((stop, index, all) => ({
...stop,
isFirst: index === 0,
isLast: index === all.length - 1
}));
}
}<!-- routeStops.html (for:each variant) -->
<template>
<ol>
<template for:each={stops} for:item="stop">
<li key={stop.id}>
<strong lwc:if={stop.isFirst}>Start: </strong>
<strong lwc:if={stop.isLast}>Finish: </strong>
{stop.name}
</li>
</template>
</ol>
</template>This produces the same output. The cost is a getter that builds a new array of new objects every time the component renders. For a few dozen items this is negligible. The benefit is that the logic is testable in plain JavaScript and can express rules that first and last cannot, such as "mark every third row".
How to decide
Start from what the template needs to know about each element, not from which directive feels more modern.
| Situation | Better choice | Reason |
|---|---|---|
| Plain list, nothing special about any element | `for:each` | Shortest form, and the item name reads clearly |
| Only the position is needed | `for:each` with `for:index` | `for:index` is a direct, named variable |
| First or last element needs different markup | `iterator` | `first` and `last` come built in |
| Rule depends on neighbors or a pattern (every third row, a group boundary) | `for:each` with prepared data | Only JavaScript can compute it |
| The same flags are needed in JavaScript, such as in a click handler | `for:each` with prepared data | The data carries the flags, so both sides see them |
| Data is already decorated for CSS classes or labels | `for:each` | Adding `isFirst` and `isLast` costs one more line |
When both directives work, prefer for:each. It is the form most LWC developers recognize, so it is easiest to review. Move to iterator when first or last removes a getter and a mapping step.
Gotchas when switching
These mistakes appear most often when someone changes from one directive to the other.
- Using
for:itemwithiterator. Theiteratordirective takes its name in the attribute itself, as initerator:it={items}. It has nofor:itemorfor:index. Useit.indexfor the position. - Forgetting
value. In an iterator loop,{it.Name}renders nothing. The element isit.value, so you need{it.value.Name}. - Putting the key on the
<template>tag. The key goes on the first real element inside the loop template. The template tag itself is not rendered. - Keying on the index. Both
for:indexandit.indexare tempting keys. They break when items are inserted, removed or reordered, because the key then points at a different record. Use the record's own Id. - Doing arithmetic in the template. To show "Stop 1" instead of "Stop 0", you cannot write
{it.index + 1}. Compute a display number in JavaScript and bind it. - Reusing the iterator name in a nested loop. An inner loop with the same name hides the outer one. Give each loop its own name, such as
rowandcell.
Quick comparison of cost
Neither directive is meaningfully faster. In both cases LWC uses the key to match old items to new ones when the array changes, so reordering and inserting work the same way. What differs is where you spend effort:
iteratormoves that effort into the template, wherefirstandlastare free.for:eachwith prepared data moves it into JavaScript. This gives you more flexibility, and you must keep the mapping correct yourself.
A good rule is to pick the version that leaves the least logic in the place that is hardest to test. Templates cannot be unit-tested for logic as easily as a getter can, so complex rules usually belong in JavaScript.
Practice
Exercise
A breadcrumb list must render a "Home" icon only on the first item and use a different class on the last item. Every item has a unique id. Which directive is the simplest fit, and what do you use as the key?
Show answer
Use iterator, because it.first and it.last give the two conditions directly. The key is it.value.id, placed on the first element inside the loop template. You should not use it.index as the key.
Exercise
A table must shade every third row. Can iterator do this with it.first and it.last? What approach would you use instead?
Show answer
No, first and last only identify the ends of the list. Use for:each over a getter that maps each element to an object with a computed field, for example cssClass: (index + 1) % 3 === 0 ? 'shaded' : ''. The template then binds class={row.cssClass}.
Exercise
This template renders blank names: <template iterator:it={contacts}><li key={it.Id}>{it.Name}</li></template>. What are the two mistakes, and what is the corrected template?
Show answer
The properties are read from it instead of it.value, so it.Id and it.Name are undefined. The corrected template is <template iterator:it={contacts}><li key={it.value.Id}>{it.value.Name}</li></template>.