Sub topic 6
Computing conditions with getters
This chapter assumes you can write a basic Lightning Web Component (an HTML template plus a JavaScript class). It also assumes you know {property} binding, reactive fields, event handlers, and JavaScript getters. You should also have seen lwc:if on its own. Here you learn how to feed it conditions that are more than a single stored flag.
Why the template cannot hold the logic
The value of lwc:if must be a plain reference to a property of the component class. The template language has no expression support. You cannot write comparisons, negation, or boolean operators inside the braces.
<template>
<!-- None of these compile or behave as intended -->
<p lwc:if={status === 'error'}>Failed</p>
<p lwc:if={!isLoading}>Done</p>
<p lwc:if={isAdmin && isActive}>Admin tools</p>
</template>The template stays declarative, and all decisions live in JavaScript where you can test and debug them. A getter is how you turn an expression into a property reference.
The basic pattern
A getter is a class member declared with get. Callers read it as a property, and the body runs on each read. Put the expression in the getter and bind the getter by name.
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
status = 'draft';
items = [];
get isSubmitted() {
return this.status === 'submitted';
}
get hasItems() {
return this.items.length > 0;
}
get isEmpty() {
return !this.hasItems;
}
handleSubmit() {
this.status = 'submitted';
}
handleAdd() {
this.items = [...this.items, { id: this.items.length + 1 }];
}
}<template>
<p lwc:if={hasItems}>You have {items.length} items.</p>
<p lwc:else>Your cart is empty.</p>
<p lwc:if={isSubmitted}>Order submitted.</p>
<button lwc:else onclick={handleSubmit}>Submit order</button>
</template>Each getter returns a single value. The template never sees === or !.
How re-evaluation works
When a reactive field that a getter reads changes, the component re-renders. During rendering the framework reads the getter again, and lwc:if adds or removes its block accordingly. You do not notify the framework about the getter. Reading this.status during render is what links the getter to the field.
All class fields are reactive when you reassign them. If you change something inside an object or array without reassigning it, such as this.items.push(x), the template may not update. Reassign instead, as handleAdd does above with the spread operator.
Common getter shapes
| Need | Getter body | Column | Column |
|---|---|---|---|
| Compare to a value | `return this.status === 'error';` | ||
| Negate a flag | `return !this.isLoading;` | ||
| Combine flags | `return this.isAdmin && this.isActive;` | ||
| Check a list | `return this.items.length > 0;` | ||
| Check for data from a wire | `return !!(this.result.data && this.result.data.length);` | ||
| Either of two states | `return this.status === 'error' \ | \ | this.status === 'timeout';` |
Name boolean getters so the template reads like a sentence. The is, has, and show prefixes are the usual convention, as in isLoading, hasError, and showDetails. Avoid negative names such as isNotReady. When you need the opposite of a condition, lwc:else usually covers it. If you need a separate negated getter, name it for what it means, such as isIncomplete.
Returning a real boolean
The directive only needs a truthy or falsy value. A getter like return this.items.length; works because 0 is falsy. Returning an explicit boolean is still clearer. It makes the getter easier to read, and it behaves the same if someone later reuses the getter in JavaScript, for example in an if that compares with === true.
You can convert with Boolean(value) or !!value. Use Boolean(...) when readability matters more than brevity.
get hasSelection() {
return Boolean(this.selectedId);
}A fuller example with a chain
Getters combine well with lwc:elseif and lwc:else. Each branch needs its own property reference, and each getter should describe one state.
import { LightningElement, api } from 'lwc';
export default class AccountBadge extends LightningElement {
@api tier;
@api isActive = false;
get isGold() {
return this.isActive && this.tier === 'gold';
}
get isSilver() {
return this.isActive && this.tier === 'silver';
}
}<template>
<span lwc:if={isGold}>Gold member</span>
<span lwc:elseif={isSilver}>Silver member</span>
<span lwc:else>Standard</span>
</template>An inactive account falls through both getters and shows "Standard". The isActive check appears in both getters. If it grows, add a third getter such as get isEligible() and reuse it inside isGold and isSilver. Getters can call other getters.
Where getters get their data
A getter is not limited to the component's own fields. It can read:
- Public properties set by a parent (
@api). - Results of
@wireadapters, such asthis.contacts.dataandthis.contacts.error. - Values set in
connectedCallbackor in event handlers.
Wired data begins as undefined, so guard against that before reading its members.
get hasContacts() {
return Boolean(this.contacts && this.contacts.data && this.contacts.data.length);
}If you wrote this.contacts.data.length > 0 without the guards, the first render would throw, because data is not yet defined.
Keep getters cheap and pure
The framework does not cache getter results. The getter runs every time the template reads it, and a re-render can read it more than once. Follow these rules:
- No side effects. Do not assign fields, fire events, or call APIs from a getter. Writing to a field during render can cause render loops or errors.
- No heavy work. Do not sort or filter large arrays inside a condition getter. Compute the result once in a handler or setter, store it in a field, and have the getter read the field.
- Deterministic results. Avoid reading
Date.now()orMath.random(). The result would change without any field change, and the template will not re-render to reflect it.
Mistakes to avoid
- Misspelled names fail quietly. If the template references
hasItemand the class defineshasItems, the template readsundefined. That is falsy, so the block never renders and no obvious error appears. When a branch never shows up, check the spelling first. - Expressions in braces. Move
!,===, and&&into a getter. This is the most frequent compile-time error with these directives. - Methods instead of getters.
lwc:if={isReady()}is not valid. A method call is an expression. Useget isReady()and bind{isReady}. - Duplicated logic. If two getters repeat the same comparison, extract a shared getter. This keeps chain branches from drifting apart.
- Overlapping conditions in a chain. In
lwc:ifandlwc:elseif, the first truthy branch wins and later ones are skipped. Overlap is safe but can hide mistakes. Write getters so each one describes a distinct state, and the chain order stops being a hidden rule.
Exercises
Exercise
A template contains <p lwc:if={count > 0}>Items found</p> and does not compile. Rewrite it so it works, and explain why the original is invalid.
Show answer
Add get hasCount() { return this.count > 0; } to the class and change the template to <p lwc:if={hasCount}>Items found</p>. The original is invalid because the value of lwc:if must be a simple property reference, and the template language does not support expressions such as count > 0. The comparison must happen in a getter.
Exercise
A component declares get hasRows() { return this.rows.length > 0; }. A handler runs this.rows.push(newRow) on a field initialized as rows = [];. The lwc:if={hasRows} block does not appear. What is the likely cause, and what is the fix?
Show answer
Pushing into the array changes it in place, and the field itself is never reassigned, so the framework may not detect the change and re-render. Reassign the field instead, for example this.rows = [...this.rows, newRow];. The getter is then read again on the next render and returns true.