Iteration(loops) in Lightning Web Components

There are two ways through which you can display list in LWC.

1. for:each

2. iterator


1. Using for:each


in this example, we are displaying a list (contacts), which have 3 fields Id, Name and Title.

You can use for:item="contact" to access current item.

You can use for:index="index" to access current index.


Note: Every item in a list must have a key. When a list changes, the framework uses the key to identify each item so that it can rerender only the item that changed. The key must be a string or a number, it can't be an object. You can’t use index as a value for key. Assign unique keys to an incoming data set. To add new items to a data set, use a private property to track and generate keys.

In this example we are using <li key={contact.Id}> to assign unique id.


2. Using iterator - The difference between for:each and iterator is that you can directly access first and last element of the list any time.


Use iteratorName to access these properties:


  1. value—The value of the item in the list. Use this property to access the properties of the array. For example,iteratorName.value.propertyName.