Use Complex Expressions to Compute Values

Template expressions support a wide range of computations within a component template. Use template expressions to reduce or eliminate the need for display-only properties or getters.

Do not use complex template expressions in production. See Considerations and Limitations for additional cautions.

Important

The Limits of Basic Property Binding 

With simple property binding, dynamically computing a value for a property used in a template requires you to:

  • Define a getter that computes the value in the component class, and then
  • Reference that getter in the template.
1<template>
2  {propertyName}
3</template>
1import { LightningElement } from "lwc";
2export default class Component extends LightningElement {
3  get propertyName() {
4    // Compute a value for propertyName
5  }
6}

Template expressions are more powerful than basic property binding. They can contain any JavaScript expression that is valid in a template context. Additionally, complex expressions can be used for inline computations, which reduces the need for getters that solely compute or format values for a component’s user interface.

Compute and Format Values for Display Using Expressions 

Template expressions are more powerful than basic property binding. They can contain any JavaScript expression that is legal in a template context. Complex expressions can be used for inline computations, which reduces the need for getters that solely compute or format values for a component’s user interface.

The following example illustrates a range of template expressions used to display user and status information. Additional examples covering specific syntax and use cases are offered throughout the documentation.

1<template>
2  <!-- Template literals -->
3  <div>{`Hello ${name}, welcome!`}</div>
4
5  <!-- Ternary operators -->
6  <div>{isLoggedIn ? 'Welcome back!' : 'Please log in'}</div>
7
8  <!-- Logical operators -->
9  <div>{user && user.name}</div>
10  <div>{error || 'No error'}</div>
11
12  <!-- Function calls -->
13  <div>{formatDate(timestamp)}</div>
14
15  <!-- Array expressions -->
16  <div>{[firstName, lastName].join(' ')}</div>
17
18  <!-- Complex chaining -->
19  <div>{user?.profile?.settings?.theme ?? 'default'}</div>
20</template>
1import { LightningElement } from "lwc";
2
3export default class ExampleComponent extends LightningElement {
4  name = "World";
5  isLoggedIn = true;
6  user = { name: "John Doe" };
7  error = null;
8  timestamp = Date.now();
9  firstName = "John";
10  lastName = "Doe";
11
12  formatDate(timestamp) {
13    return new Date(timestamp).toLocaleDateString();
14  }
15}