Class Getter Setter in JavaScript

Level 4241 keystrokes

Getters and setters allow controlled access to object properties using method-like syntax.

JavaScript code

// Define a Circle class
1class Circle {
// Constructor initializes the radius
2 constructor(radius) {
// Store radius with underscore convention for private
3 this._radius = radius;
4 }
// Getter returns calculated diameter
5 get diameter() {
// Diameter is radius times 2
6 return this._radius * 2;
7 }
// Setter allows changing radius
8 set radius(value) {
// Update the internal radius value
9 this._radius = value;
10 }
11}
// Create a circle with radius 5
12const c = new Circle(5);
// Access diameter via getter (returns 10)
13console.log(c.diameter);
// Use setter to change radius
14c.radius = 10;
// Diameter is now 20
15console.log(c.diameter);

Output

10
20
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • .× 8
  • ;× 7
  • (× 6
  • )× 6
  • {× 4
  • }× 4
  • =× 4
  • _× 3
  • *× 1

More JavaScript examples at level 4

← JavaScript typing practice