Sub topic 3
How a condition is evaluated: truthy and falsy values
This chapter assumes you can read an LWC template and its JavaScript class, and that you know how {property} binding works. It also assumes you know what a getter is. The directive syntax is covered in the next chapters. Here the focus is narrower: when you give lwc:if a value, how does LWC decide whether that value means "render" or "don't render"?
The rule: JavaScript truthiness
lwc:if does not require a boolean. It accepts any value and converts it the way JavaScript converts a value in an if statement. If the value is truthy, the block renders. If it is falsy, the block does not render.
Only a short list of values is falsy. Everything else is truthy.
| Value | Type | Falsy? |
|---|---|---|
| `false` | boolean | Yes |
| `0` and `-0` | number | Yes |
| `0n` | BigInt | Yes |
| `""` (empty string) | string | Yes |
| `null` | null | Yes |
| `undefined` | undefined | Yes |
| `NaN` | number | Yes |
| `true` | boolean | No |
| `1`, `-1`, `3.14` | number | No |
| `"0"`, `"false"`, `" "` | string | No |
| `[]` (empty array) | object | No |
| `{}` (empty object) | object | No |
Memorize the falsy list. Anything not on it is truthy, including some values that look empty or negative at first glance.
Seeing it in a running component
The component below exposes several values of different types. Each one drives its own lwc:if block, so you can see which ones render.
<template>
<ul>
<li lwc:if={emptyString}>emptyString rendered</li>
<li lwc:if={zero}>zero rendered</li>
<li lwc:if={nothing}>nothing rendered</li>
<li lwc:if={textZero}>textZero rendered</li>
<li lwc:if={emptyArray}>emptyArray rendered</li>
<li lwc:if={emptyObject}>emptyObject rendered</li>
<li lwc:if={name}>name rendered</li>
</ul>
</template>import { LightningElement } from 'lwc';
export default class TruthinessDemo extends LightningElement {
emptyString = '';
zero = 0;
nothing = null;
textZero = '0';
emptyArray = [];
emptyObject = {};
name = 'Ada';
}This component renders three list items: textZero, emptyArray, and emptyObject. Wait, that count is wrong without name. The correct result is four items: textZero rendered, emptyArray rendered, emptyObject rendered, and name rendered. The first three fields are falsy and render nothing. The string '0' is a non-empty string, so it is truthy. The empty array and empty object are objects, and every object is truthy, regardless of its contents.
Why the evaluation happens where it does
LWC re-evaluates each directive every time the component renders. A render happens when a reactive value that the template reads changes. For a field, the engine tracks reassignment. For objects and arrays, it tracks changes to the properties of the object, as long as the field is set up for that tracking.
The sequence looks like this:
Two consequences follow from this model.
- The condition is a snapshot of the value at render time. If you change a value that the template does not read, nothing re-renders and the branch stays as it was.
- A falsy result does not hide the block. It leaves the block out of the DOM entirely. A later chapter covers what that means for child components.
Using truthiness on purpose
Truthiness lets you write short templates when the data already has the right shape.
A common case is optional data that arrives later. Before a record loads, a field holds undefined. After it loads, it holds an object:
<template>
<p lwc:if={account}>Account: {account.Name}</p>
<p lwc:else>No account loaded yet.</p>
</template>import { LightningElement } from 'lwc';
export default class AccountLabel extends LightningElement {
account;
connectedCallback() {
// Simulates data that arrives after the first render.
setTimeout(() => {
this.account = { Name: 'Acme' };
}, 1000);
}
}First account is undefined, which is falsy, so the lwc:else text shows. After the assignment, account is an object, which is truthy, so the first paragraph renders and account.Name is safe to read. Binding a dotted path like account.Name inside the block works because the block only exists when account is truthy.
A second case is text input. An empty string is falsy, so a block bound to a text field hides itself when the user clears the box:
<template>
<lightning-input label="Name" onchange={handleChange}></lightning-input>
<p lwc:if={name}>Hello, {name}!</p>
<p lwc:else>Type your name above.</p>
</template>import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
name = '';
handleChange(event) {
this.name = event.target.value;
}
}Where truthiness misleads you
The same rule that makes short templates possible also causes the most common bugs. The values that surprise people fall into four groups.
Zero is falsy, which may not be what you meant
If lwc:if={count} guards a block that shows a count, a count of zero hides the block. That can be correct ("show the badge only when there is something to count"). It is a bug if you wanted to display "0 items". Decide which behavior you want before you bind the raw number.
Empty collections are truthy
lwc:if={items} renders when items is []. If you want to know whether the list has entries, use the length. A getter makes the intent clear:
import { LightningElement } from 'lwc';
export default class ItemList extends LightningElement {
items = [];
get hasItems() {
return this.items.length > 0;
}
}<template>
<p lwc:if={hasItems}>You have {items.length} items.</p>
<p lwc:else>Your list is empty.</p>
</template>Templates cannot contain comparisons such as items.length > 0 or negation such as !isDone. The condition has to be a property, a dotted path, or a getter. The next chapters cover getters in detail.
Strings from attributes are not booleans
An attribute written in HTML is a string. If a parent writes <c-panel is-open="false">, the child receives the string "false". That string is non-empty, so it is truthy, and the block renders.
For a public boolean property, pass a bound value from JavaScript, or rely on attribute presence for true:
<template>
<!-- isOpen is a boolean field in the parent's class -->
<c-panel is-open={isOpen}></c-panel>
</template>Also give boolean public properties a default of false. A property that defaults to true cannot be turned off by omitting the attribute.
Values from outside code may not be the type you expect
Data from Apex, wire adapters, and event payloads can arrive as null, undefined, or a string such as "0". If you bind these values directly, test them with real data. When the type is uncertain, convert it yourself in a getter.
Making the conversion explicit
A getter that returns a real boolean documents your intent and avoids surprises when the underlying data changes type. Two common forms:
import { LightningElement } from 'lwc';
export default class Badge extends LightningElement {
unreadCount = 0;
statusText = '';
// Show the badge only when the count is above zero.
get showBadge() {
return this.unreadCount > 0;
}
// Double negation converts any value to true or false.
get hasStatus() {
return !!this.statusText;
}
}!!value applies truthiness and returns the matching boolean. It gives the same answer as binding the raw value, but it makes the conversion visible to the next reader. A comparison such as > 0 goes further and says exactly what you mean.
Quick checklist
- Falsy values:
false,0,-0,0n,"",null,undefined,NaN. Everything else is truthy. [],{},"0", and"false"are truthy.- The condition is read at render time, and the template re-renders when a value it reads changes.
- A falsy condition removes the block from the DOM. It does not hide it.
- Use getters for comparisons, negation, and length checks, because the template cannot express them.
Exercise
A component has the field results = [] and the template <p lwc:if={results}>Showing results</p>. Does the paragraph render? What would you change so that it renders only when there is at least one result, and what does the template need in order to use your change?
Show answer
The paragraph renders, because an empty array is an object and every object is truthy. To render only when results exist, add a getter to the class, such as get hasResults() { return this.results.length > 0; }, and bind it with <p lwc:if={hasResults}>Showing results</p>. The getter is needed because the template cannot contain a comparison such as results.length > 0.
Exercise
A parent writes <c-panel is-open="false"></c-panel> and the child's isOpen property controls an lwc:if block. The block renders even though the parent wrote "false". Why, and how do you fix it?
Show answer
HTML attributes are strings. The value "false" is a non-empty string, so it is truthy and the block renders. Fix it by binding a real boolean from the parent's JavaScript, for example is-open={isOpen} where isOpen is false, or by omitting the attribute when the panel should be closed.