Overview
Iteration allows you to render lists of data in your Lightning Web Components. LWC provides two directives for rendering arrays:for:each for simple lists and iterator for advanced scenarios where you need access to index or first/last information.
for:each Directive
Thefor:each directive is the most common way to render lists. It’s simple, performant, and ideal for most use cases.
Implementation
Key Concepts for for:each
The for:each Attribute
for:each={contacts}- The array to iterate overfor:item="contact"- The variable name for each item (in quotes)- Inside the template, access the current item using
{contact}
The key Attribute
The
key attribute is required for all elements inside a for:each loop. It must be a unique identifier for each item.- Helps LWC efficiently update the DOM when the list changes
- Must be unique within the list
- Should be stable (same item always has the same key)
What You’ll See
The component renders a bulleted list:- Amy Taylor, VP of Engineering
- Michael Jones, VP of Sales
- Jennifer Wu, CEO
iterator Directive
Theiterator directive provides access to additional metadata about each iteration, including whether an item is first or last in the list.
Implementation
Key Concepts for iterator
The iterator Attribute
iterator:it={contacts}- Creates an iterator nameditfor thecontactsarray- The iterator name (
it) can be any valid identifier
Iterator Properties
The iterator object provides several properties:it.value- The current item in the arrayit.index- The zero-based index of the current itemit.first-trueif this is the first itemit.last-trueif this is the last item
What You’ll See
The component renders a list with special markers:- (first marker) Amy Taylor, VP of Engineering
- Michael Jones, VP of Sales
- Jennifer Wu, CEO (last marker)
When to Use Each Directive
Use for:each when:
- You have a simple list to render
- You don’t need index or first/last information
- You want cleaner, more readable templates
Use iterator when:
- You need to know if an item is first or last
- You need the item’s index
- You want to apply special styling to boundary items
- You need to add separators between items
Common Patterns
Nested Arrays
Conditional Items
Item Separators
Best Practices
Iterate over arrays only: The
for:each and iterator directives work only with arrays, not objects. To iterate over object properties, convert them to an array first.Converting Objects to Arrays
If you need to iterate over object properties:Performance Considerations
Large lists: For very large lists (1000+ items), consider:
- Virtual scrolling or pagination
- Lazy loading as users scroll
- Filtering to reduce visible items
Next Steps
- Conditional Rendering - Combine with iteration to show/hide items
- Expressions - Compute values for list items
- Data Binding - Handle events from list items
