Course contentsShow
← JavaScript
Lesson 663 of 2,72316. Object Methods and PatternsFree lesson

Using Getters for Computed Properties

Create dynamic properties that calculate their value on-the-fly based on other object properties.

Using Getters for Computed Properties

You'll learn how to create object properties that automatically calculate their values based on other properties, without storing redundant data.

The Core Idea

A computed property is a value that's derived from other properties instead of being stored directly. Getters are perfect for this because they run a calculation every time you access the property, ensuring the value is always up-to-date.

Think of it like asking someone their age. They don't store their age separately—they calculate it on-the-spot from their birth year and the current year. The getter does the math for you automatically.

Why Use Getters for Computation?

Instead of storing a value that might become outdated, you let the getter compute it fresh each time:

const rectangle = {
  width: 10,
  height: 5,
  
  get area() {
    return this.width * this.height;
  }
};

console.log(rectangle.area); // 50

rectangle.width = 20;
console.log(rectangle.area); // 100 (automatically updated!)

Notice how area isn't stored anywhere—it's calculated from width and height whenever you access it. No extra storage, no risk of stale data.

Common Use Cases

const person = {
  firstName: 'Jane',
  lastName: 'Doe',
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(person.fullName); // "Jane Doe"

The fullName getter combines two properties into one convenient computed property. You access it like a normal property, but it's dynamically generated.

Key Takeaway: Getters let you define properties that compute their values on-the-fly from other object properties, keeping your data consistent without storing redundant information.