Getter and Setter in JavaScript
Level 4268 keystrokes
Uses getter and setter to control access to class properties.
JavaScript code
// Define a Circle class1class Circle { // Constructor runs when creating a new instance2 constructor(radius) { // _radius is a convention for "private" property3 this._radius = radius;4 } // get keyword defines a getter - accessed like a property5 get radius() {6 return this._radius;7 } // set keyword defines a setter - validates before setting8 set radius(value) { // Only set if value is positive9 if (value > 0) this._radius = value;10 } // Computed property that calculates area on access11 get area() { // ** is the exponentiation operator (radius squared)12 return Math.PI * this._radius ** 2;13 }14}// Create a circle with radius 515const c = new Circle(5);// Access area getter and format to 2 decimal places16console.log(c.area.toFixed(2));Output
78.54
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(× 8)× 8;× 6{× 5}× 5_× 4*× 3=× 3>× 1