Menu
Coddy logo textTech

Computed Properties

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 44 of 56.

Computed properties are getters that calculate and return a value instead of just returning stored data. They look like regular properties but compute their value on-the-fly.

Let's have a look at the example. We have an object with a regular property:

const circle = {
  radius: 5
};

Now we add a computed property using a getter:

const circle = {
  radius: 5,
  get diameter() {
    return this.radius * 2;
  }
};

This is how we access the computed property:

console.log(circle.diameter); // Outputs: 10

If we update the radius, the diameter automatically updates too:

circle.radius = 10;
console.log(circle.diameter); // Outputs: 20

Computed properties are useful when a property's value depends on other properties or requires calculation.

challenge icon

Challenge

You're given a Rectangle class with width and height properties. Your task is to add computed properties for area and perimeter.

  1. Computed property <strong>area</strong> - returns width × height
  2. Computed property <strong>perimeter</strong> - returns 2 × (width + height)

Cheat sheet

Computed properties are getters that calculate and return a value instead of just returning stored data. They compute their value on-the-fly.

Define a computed property using the get keyword:

const circle = {
  radius: 5,
  get diameter() {
    return this.radius * 2;
  }
};

Access computed properties like regular properties (without parentheses):

console.log(circle.diameter); // Outputs: 10

Computed properties automatically update when their dependent properties change:

circle.radius = 10;
console.log(circle.diameter); // Outputs: 20

Try it yourself

import { Rectangle } from './rectangle.js';

// Test code - don't modify
const rect = new Rectangle(5, 10);
console.log(`Area: ${rect.area}`);        // Should output "Area: 50"
console.log(`Perimeter: ${rect.perimeter}`); // Should output "Perimeter: 30"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming