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: 10If we update the radius, the diameter automatically updates too:
circle.radius = 10;
console.log(circle.diameter); // Outputs: 20Computed properties are useful when a property's value depends on other properties or requires calculation.
Challenge
You're given a Rectangle class with width and height properties. Your task is to add computed properties for area and perimeter.
- Computed property
<strong>area</strong>- returns width × height - 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: 10Computed properties automatically update when their dependent properties change:
circle.radius = 10;
console.log(circle.diameter); // Outputs: 20Try 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"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge12Getters & Setters
The get and set KeywordsComputed PropertiesValidation and Side EffectsRecap Challenge