Sub topic 5
Computing values with getters
This chapter assumes you can write a basic Lightning Web Component (LWC) bundle and read modern JavaScript classes. You should also know that {property} in a template reads a field from the component class. Here you will learn what a getter is, how the template uses it, and where getters go wrong.
The problem getters solve
An LWC template can only reference a property by name. It cannot multiply two numbers, compare values, call a method with arguments, or join strings. If the template needs quantity * unitPrice, you cannot write that expression inside the braces.
The fix is to move the computation into JavaScript and give the result a name. A JavaScript getter does this. A getter is a class member declared with the get keyword. You read it like a field, with no parentheses, but each read runs a function.
// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
}The template binds to total exactly as it would bind to a field:
<!-- orderSummary.html -->
<template>
<p>Total: {total}</p>
</template>The template does not know whether total is a field or a getter. It only asks the component for a property called total. That is why getters fit LWC well. The template stays simple and all logic stays in the class, where you can test it.
How a getter runs
A getter has no stored value of its own. The engine calls the function every time the template renders and reads the result. Three facts follow from this.
- It is always current. The getter reads
this.quantityandthis.unitPriceat render time, so it never returns a stale value. - It re-runs on every render. The result is not cached between renders. A render happens when any field the template reads changes, so a getter may run more often than you expect.
- It has no way to be assigned. A getter without a matching setter is read-only. Writing
this.total = 10fails or does nothing, depending on the environment.
The sequence looks like this:
The getter is not what triggers the render. A field change does, and the getter just runs as part of the render. If the getter reads a field that never changes, its result stays the same. If it reads a field that changes, the new value shows up the next time the template renders.
Getters for display values
The simplest use is formatting or combining data for display. Template literals work well for this.
// fullName.js
import { LightningElement } from 'lwc';
export default class FullName extends LightningElement {
firstName = 'Ada';
lastName = 'Lovelace';
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}Rules that apply to every getter:
- Use
this.to read fields. Without it, JavaScript looks for a local variable and throws aReferenceError. - Always
returna value. A getter with no return givesundefined, and the template renders nothing. - Give it a name that does not collide with a field. Declaring both a field
totaland a gettertotalin one class is an error.
Getters for conditions
Directives such as lwc:if accept only a property reference, so a comparison has to live in a getter. Name boolean getters like questions: hasItems, isEmpty, canSubmit.
// 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;
}
}<!-- cart.html -->
<template>
<template lwc:if={hasItems}>
<p>You have {itemCount} items in your cart.</p>
</template>
<template lwc:else>
<p>Your cart is empty.</p>
</template>
</template>You cannot write lwc:if={items.length > 0} and you cannot write lwc:if={!hasItems}. Negation is not supported either. If you need the opposite of a condition, write a second getter such as isEmpty, or use lwc:else.
Getters for strings that drive attributes
An attribute binding also takes a property reference. A getter is how you pick a CSS class from state. This getter pair comes from a small form where the message changes with the input:
// greeter.js
import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
name = '';
handleChange(event) {
this.name = event.target.value;
}
get message() {
return this.name ? `Hello, ${this.name}!` : 'Please enter your name.';
}
get messageClass() {
return this.name ? 'slds-text-color_success' : 'slds-text-color_weak';
}
}<!-- greeter.html -->
<template>
<lightning-input label="Your name" value={name} onchange={handleChange}></lightning-input>
<p class={messageClass}>{message}</p>
</template>Typing in the input calls handleChange, which reassigns name. That reassignment causes a re-render, and both getters run again with the new value. Neither getter has to be told that name changed.
When a class string has several parts, build it from an array to avoid stray spaces:
get statusClass() {
return ['slds-badge', this.isActive ? 'slds-theme_success' : 'slds-theme_offline']
.join(' ');
}Getters that reshape lists
for:each needs an array, and each item needs a unique key. Raw data often lacks a display-ready label, so a getter can map it into the shape the template wants.
// 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}`
}));
}
}<!-- contactList.html -->
<template>
<ul>
<template for:each={displayContacts} for:item="contact">
<li key={contact.id}>{contact.label}</li>
</template>
</ul>
</template>map returns a new array and leaves this.contacts unchanged. This is the safe pattern. The getter produces a view of the data, and the original stays the single source of truth. The key must be a stable, unique value such as an id. An array index or a random number defeats the purpose of the key.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `{quantity * unitPrice}` in the template | Compile error | Add a `total` getter |
| `{getTotal()}` in the template | Compile error, templates cannot call methods | Use `get total()` and write `{total}` |
| `this.total = 5` on a getter-only property | Assignment fails or is ignored | Change the fields the getter reads |
| Forgetting `this.` inside the getter | `ReferenceError` | Write `this.quantity` |
| Forgetting `return` | Template shows nothing | Return the value |
| Getter and field share a name | Class declaration error | Rename one of them |
| Getter returns a new array each render but the key is missing or non-unique | Warnings and wrong DOM reuse | Return an id and bind `key={item.id}` |
Cost and when to avoid a getter
Because a getter re-runs on every render, cheap work is fine and expensive work is not. Filtering a list of ten items is trivial. Sorting thousands of records on every keystroke elsewhere in the component is not.
If a computation is costly and its inputs change rarely, compute it once in the code that changes the inputs, such as an event handler or a data callback, and store the result in a field. The template then binds to that field. Choose based on how often the inputs change compared with how often the component renders.
Exercises
Exercise
A template contains <p>{price * 1.2}</p>. It fails to compile. Rewrite it so the price including 20% tax shows in the paragraph. Show the getter and the template line.
Show answer
Add a getter and bind to it. In the class: get priceWithTax() { return this.price * 1.2; }. In the template: <p>{priceWithTax}</p>. The template can only reference a property by name, so the multiplication moves into the getter.
Exercise
You want to show a "Checkout" section only when a cart array has at least one item and a user field is set. Which part belongs in the template and which in the class?
Show answer
The class holds a getter such as get canCheckout() { return this.cart.length > 0 && Boolean(this.user); }. The template uses <template lwc:if={canCheckout}>. The directive accepts only a property reference, so the comparison and the && must be computed in JavaScript.
Exercise
A developer writes a getter that increments this.renderCount every time it runs. Why is this a bad idea?
Show answer
Getters run during rendering and may run many times. Assigning to a field inside a getter is a side effect. If the template reads that field, it can trigger another render, which runs the getter again, and the component can loop. Getters should only read state and return a value.