Sub topic 5
Computing values with getters
This chapter assumes you can write a basic Lightning Web Component bundle (HTML, JS and meta XML files) and know modern JavaScript classes and template literals. You should also know that {property} in a template reads a field from the component class.
Why getters exist
LWC templates accept only a property name inside braces. An expression such as {quantity * unitPrice} or {items.length > 0} is a compile error. The template stays simple, and the JavaScript class holds all the logic.
A getter is the standard fix. It is a class member declared with get. It runs code and returns a value, and the template binds to it like any other property.
// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
}<!-- orderSummary.html -->
<template>
<p>Total: {total}</p>
</template>The template writes {total}, not {total()}. A getter is read like a field, so it has no parentheses at the call site.
How a getter stays up to date
The framework re-renders a template when a reactive field that the render read has changed. Since the getter runs during rendering, any field it reads becomes a dependency. When quantity changes, the template renders again, the getter runs again, and total shows the new value. You never have to notify the template.
Getters for different kinds of values
The same pattern covers three common needs: numbers or strings for text, booleans for conditions, and strings for attributes.
// cart.js
import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
items = ['Pen', 'Notebook'];
get itemCount() {
return this.items.length;
}
get hasItems() {
return this.items.length > 0;
}
}itemCount returns a number for display. hasItems returns a boolean that a directive such as lwc:if can use. A third getter could return a CSS class string for class={messageClass}. Later chapters cover those directives in detail. The point here is that every computed value starts as a getter.
// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ id: '1', firstName: 'Ada', lastName: 'Lovelace' },
{ id: '2', firstName: 'Alan', lastName: 'Turing' }
];
get displayContacts() {
return this.contacts.map((c) => ({
id: c.id,
label: `${c.firstName} ${c.lastName}`
}));
}
}A getter can also reshape data. displayContacts builds a new array where each item has an id and a ready-made label. The template then binds to simple properties such as {contact.label}.
Common errors
- Writing an expression in the template.
{a + b}fails to compile. Move it into a getter. - Calling the getter with parentheses.
{total()}is invalid. Use{total}. - Forgetting
this. Inside the class,quantityalone is an undefined variable. Usethis.quantity. - Assigning to a getter. A getter without a matching setter is read-only.
this.total = 10fails or does nothing useful. Change the underlying fields instead. - Putting side effects in a getter. The framework can run a getter on every render. Do not make network calls, change other fields, or log in a getter. Keep it a pure calculation from existing state.
Keep getters cheap
Since getters can run on each render, avoid heavy work in them, such as sorting a large array. If a calculation is costly, compute it once when the source data changes, store the result in a field, and bind to that field. For small arithmetic, string building and map over short lists, a getter is the right tool.
Exercise
A component has the fields price = 20 and discount = 0.25. The template needs to show the discounted price. Why does <p>{price * (1 - discount)}</p> fail, and how do you fix it?
Show answer
LWC templates allow only simple property references inside braces, so the expression does not compile. Add a getter to the class, such as get discountedPrice() { return this.price * (1 - this.discount); }, and write <p>{discountedPrice}</p> in the template. The getter re-runs whenever price or discount changes, so the displayed value stays current.
Exercise
Why should a getter not call a server or assign to other fields?
Show answer
The framework may run a getter on every render. A server call would repeat constantly, and assigning to a field the render reads can cause another render, which runs the getter again. Getters should be pure calculations from existing state.