Beginner 15 min read

Properties, Fields, and Getters

By the end of this lesson, you'll be able to:

  • Declare a reactive class field on a component
  • Write a getter for a value computed from other properties
  • Explain why getters, not stored fields, should hold derived values

Prerequisites: "The Component Lifecycle"

Class Fields Are Reactive by Default

import { LightningElement } from 'lwc';

export default class Counter extends LightningElement {
    count = 0;

    handleIncrement() {
        this.count += 1;
    }
}

A plain field like count is automatically tracked — when it changes, any part of the template referencing {count} re-renders. You don't need to manually declare reactivity for simple values like this.

Getters for Computed Values

get doubled() {
    return this.count * 2;
}

A getter runs its logic fresh every time it's read — it's never stored directly, and it always reflects the current state of whatever it depends on. Bind it in the template exactly like a field: {doubled}.

A Worked Example

import { LightningElement } from 'lwc';

export default class OrderSummary extends LightningElement {
    itemCount = 3;
    pricePerItem = 25;

    get totalPrice() {
        return this.itemCount * this.pricePerItem;
    }
}
<p>{itemCount} items at R{pricePerItem} each — total: R{totalPrice}</p>

totalPrice is never out of sync, because it's calculated fresh from itemCount and pricePerItem every single time it's read.

Why This Matters in Real Projects

An isPastDue getter derived from a dueDate field is always correct. A manually-maintained boolean field you update yourself whenever dueDate changes can silently drift out of sync the moment you forget one update site — a real, common source of bugs in larger components.

Exercise

Write a getter named fullName that combines firstName and lastName fields with a space between them.

Show hint

A getter is just a method prefixed with the get keyword.

JAVASCRIPT

Exercise

Challenge: a teammate tries to write this.doubled = 10; to directly set a getter's value. Explain, as a comment, why this fails, and what should be done instead.

Show hint

Getters are read-only by nature.

JAVASCRIPT

Properties, Fields, and Getters Quiz

1. Are plain class fields on a LightningElement reactive by default?

2. When does a getter's logic run?

3. A getter can be directly assigned a new value, just like a normal field.

4. Why is a getter preferred over a manually-maintained "derived" field?

5. In the OrderSummary example, what does totalPrice depend on?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Plain class fields are reactive by default, and getters compute derived values fresh on every read — together they show how an LWC component's data model stays both simple and correct.