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 class1class Circle { // Constructor initializes the radius2 constructor(radius) { // Store radius with underscore convention for private3 this._radius = radius;4 } // Getter returns calculated diameter5 get diameter() { // Diameter is radius times 26 return this._radius * 2;7 } // Setter allows changing radius8 set radius(value) { // Update the internal radius value9 this._radius = value;10 }11}// Create a circle with radius 512const c = new Circle(5);// Access diameter via getter (returns 10)13console.log(c.diameter);// Use setter to change radius14c.radius = 10;// Diameter is now 2015console.log(c.diameter);Output
10 20
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