Overview
ThehelloIterator component demonstrates advanced iteration in Lightning Web Components using the iterator directive. Unlike for:each, the iterator provides additional metadata about each item’s position in the array, allowing you to apply special behavior to the first and last items.
What It Does
This component displays a list of contacts with special styling or behavior for the first and last items. The iterator provides access to properties likefirst, last, index, and value, enabling more sophisticated list rendering scenarios.
Component Code
Key Concepts
- iterator Directive: Provides enhanced iteration with metadata about each item
- Iterator Properties:
value: The current item in the arrayindex: The zero-based index of the current itemfirst: Boolean indicating if this is the first itemlast: Boolean indicating if this is the last item
- Accessing Item Data: Use
it.value.propertyNameto access properties of the current item - Conditional Rendering: Combine with
lwc:ifto apply special behavior to specific items
How It Works
- The
iterator:itdirective creates an iterator variable namedit - For each contact in the array, the iterator provides:
it.value: The contact objectit.first:trueonly for Amy Taylor (first item)it.last:trueonly for Jennifer Wu (last item)it.index: 0, 1, or 2 respectively
- The
keyusesit.value.Idto uniquely identify each list item - Special divs are rendered for the first and last items using
lwc:if - Contact information is displayed using
it.value.Nameandit.value.Title
Iterator Properties Reference
| Property | Type | Description |
|---|---|---|
value | any | The current item from the array |
index | number | Zero-based index of the current item |
first | boolean | true if this is the first item |
last | boolean | true if this is the last item |
Usage Example
To use this component in your Salesforce org:When to Use iterator vs for:each
Useiterator when you need:
- To identify the first or last item in a list
- Access to the item’s index
- Special styling or behavior for specific positions
- Separators between items (but not before first or after last)
for:each when you:
- Need simple iteration without positional metadata
- Want cleaner, more concise template syntax
- Don’t need to know if an item is first, last, or its index
