Sub topic 9
Preparing display values in JavaScript
This chapter assumes you know basic HTML and JavaScript, including arrays and map. It also assumes you know how an LWC component pairs an HTML template with a class that extends LightningElement. You should be able to bind a property with curly braces and use lwc:if. You should also have rendered a list with for:each and given each item a key.
Why the template cannot do the work
An LWC template binds to properties. It does not evaluate JavaScript. These forms are all invalid inside a template:
{contact.Id === selectedId}{contact.Name.toUpperCase()}{amount * 1.2}class={isSelected ? 'selected' : ''}
The compiler accepts only a property path such as {contact.Name}. That includes a getter on the component, but it excludes any operator or function call.
This matters most inside a list. Each item may need its own CSS class, formatted text, or flag, and the template has no way to compute them. You compute them in JavaScript, then bind the results.
The pattern has three steps:
- Keep the raw data in a field.
- Write a getter that maps the raw data to display objects.
- Point
for:eachat the getter.
A getter that decorates each item
Here is the pattern with the contact list from earlier chapters. The component tracks which contact is selected. Each rendered item needs a CSS class that depends on that selection.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedId ? 'selected' : ''
}));
}
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}
addContact() {
this.contacts = [
...this.contacts,
{ Id: '003C', Name: 'New Contact' }
];
}
}The template loops over decoratedContacts instead of contacts:
<template>
<ul lwc:if={hasContacts}>
<template for:each={decoratedContacts} for:item="contact">
<li key={contact.Id}
class={contact.cssClass}
data-id={contact.Id}
onclick={handleSelect}>
{contact.Name}
</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>The map callback returns a new object for each contact. The spread (...contact) copies every original property, including Id and Name. The new cssClass property is added on top. The template then reads contact.cssClass like any other property.
Three details are worth noting:
- The decorated object still has
Id, sokey={contact.Id}stays stable between renders. The key comes from your data, not from the decoration step. - The original
contactsarray is not modified. The getter builds a fresh array each time it runs. hasContactsis a second getter. It exists because the template cannot writecontacts.length > 0.
Why the getter re-runs when data changes
When a component renders, LWC records which fields the render read. This includes reads that happen inside getters. decoratedContacts reads this.contacts and this.selectedId, so a change to either field schedules a re-render. During that render the getter runs again and produces a new array.
For this reason, handleSelect only has to assign this.selectedId. It does not touch the list or the classes. The getter derives the classes from the state every time.
The same applies to addContact. It assigns a new array to this.contacts, and the getter picks that up on the next render. The array assignment itself is covered in the chapter on updating lists.
What belongs in a decorated item
Display values come in a few recurring kinds. The table lists the common ones.
| Need | Derived property | Example value |
|---|---|---|
| Per-item CSS class | `cssClass` | `'slds-item selected'` |
| Boolean for `lwc:if` inside the loop | `isClosed` | `true` |
| Formatted number or currency | `amountText` | `'$1,200.50'` |
| Formatted date | `dateText` | `'Nov 2, 2026'` |
| Readable label for a code | `statusLabel` | `'In progress'` |
| ARIA state as a string | `ariaSelected` | `'true'` |
| Disabled state for a button | `isDisabled` | `false` |
A second example shows several of these together. Each order has a status code, an amount, and an ISO date string.
import { LightningElement } from 'lwc';
const STATUS_LABELS = { N: 'New', P: 'In progress', C: 'Closed' };
export default class OrderList extends LightningElement {
orders = [
{ Id: '801A', Amount: 1200.5, Status: 'N', CreatedDate: '2026-11-02T09:30:00.000Z' },
{ Id: '801B', Amount: 89, Status: 'P', CreatedDate: '2026-11-15T14:00:00.000Z' },
{ Id: '801C', Amount: 5400, Status: 'C', CreatedDate: '2026-10-28T08:15:00.000Z' }
];
get displayOrders() {
const currency = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
return this.orders.map((order) => ({
...order,
amountText: currency.format(order.Amount),
statusLabel: STATUS_LABELS[order.Status] ?? 'Unknown',
isClosed: order.Status === 'C',
dateText: new Date(order.CreatedDate).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
timeZone: 'UTC'
})
}));
}
}<template>
<ul>
<template for:each={displayOrders} for:item="order">
<li key={order.Id}>
{order.Id}: {order.amountText}, {order.statusLabel}, {order.dateText}
<span lwc:if={order.isClosed}> (archived)</span>
</li>
</template>
</ul>
</template>The formatter is created once per getter call, outside the map, so the loop does not build a new Intl.NumberFormat for every item. The ?? 'Unknown' fallback keeps an unexpected status code from rendering the text undefined. Passing timeZone: 'UTC' makes the date text the same on every machine. Remove it if you want the user's local time zone.
The boolean isClosed shows the usual way to branch inside a loop. The template cannot compare order.Status to 'C', so the getter does the comparison and the template tests the result.
Building CSS classes with several parts
A class string often has a base class plus conditional parts. Build it in JavaScript:
get decoratedContacts() {
return this.contacts.map((contact) => {
const classes = ['contact-row'];
if (contact.Id === this.selectedId) {
classes.push('selected');
}
if (!contact.Email) {
classes.push('missing-email');
}
return { ...contact, cssClass: classes.join(' ') };
});
}An array joined with spaces avoids stray double spaces and leading spaces that string concatenation tends to produce.
Getter or stored field
A getter is not the only way to hold derived data. You can also compute the decorated array in a handler and store it in a field. The two approaches differ as follows.
| Question | Getter | Stored field |
|---|---|---|
| Can it fall out of sync with the source? | No. It recomputes from current state. | Yes, if you forget to update it in one code path. |
| When does the work run? | On each render that reads it. | Only when you run it. |
| Good for | Small and medium lists, cheap transformations. | Expensive work, such as sorting thousands of rows. |
Start with a getter. Switch to a stored field only when measurement shows that the getter's cost matters. Keep one source of truth, and treat the decorated array as a view of it.
Pitfalls
- Mutating inside the getter. A getter should return a value and change nothing. Writing to
this.selectedIdor modifyingcontact.cssClasson the original object inside a getter causes extra renders or errors. Always return new objects. - Referencing the getter many times. Each use of
{displayOrders}in the template, such as a second loop, runs the getter again. Use it once per render path, or store the result. - Forgetting the spread. If you return
{ cssClass: '...' }without...contact, the new object has noIdorName, andkey={contact.Id}resolves toundefined. - Shallow copies. The spread copies top-level properties only. Nested objects and arrays are shared with the original. Do not mutate them through the decorated item.
- Random or index keys. Do not add
key: Math.random()to the decoration. A new key on every render makes LWC discard and rebuild each element. Take the key from a stable identifier such asId. - Binding to the wrong array. If the template still iterates
contacts, thencontact.cssClassisundefinedand no class is applied. This produces no error, so check which arrayfor:eachpoints to.
Checking your work
To confirm the decoration works, add a temporary line to the template, such as {contact.cssClass}, inside the li. The text shows what the getter produced for each row. Remove it once the class values look right. In the browser's developer tools, inspect the li elements and check that the class and data-id attributes match the data.
Exercise
A component has tasks = [{ Id: 't1', Title: 'Write', Done: false }, { Id: 't2', Title: 'Review', Done: true }]. Write a getter named displayTasks that returns each task with two extra properties. statusText should be 'Done' or 'Open'. cssClass should be 'task done' when the task is done and 'task' otherwise. Then say why the template cannot do this comparison itself.
Show answer
``javascript is not needed here; the getter is: get displayTasks() { return this.tasks.map((task) => ({ ...task, statusText: task.Done ? 'Done' : 'Open', cssClass: task.Done ? 'task done' : 'task' })); }. The template then loops over displayTasks with key={task.Id} and binds {task.statusText} and class={task.cssClass}. The template cannot do it because LWC templates accept only property bindings. They do not allow the ternary operator, comparisons, or function calls. The spread keeps Id so the key stays stable, and map returns new objects so the original tasks` array is not changed.
Exercise
Your decoratedContacts getter returns { cssClass: 'selected' } for each item and omits ...contact. The list renders, but React-style key warnings appear and clicking rows selects the wrong item. What is the likely cause, and how do you fix it?
Show answer
Without the spread, the decorated objects have no Id, so key={contact.Id} and data-id={contact.Id} resolve to undefined. The keys are not unique, and the click handler reads an undefined dataset.id. Add ...contact before cssClass in the returned object so Id and Name are copied across.