Getter and Setter in JavaScript

Level 4268 keystrokes

Uses getter and setter to control access to class properties.

JavaScript code

// Define a Circle class
1class Circle {
// Constructor runs when creating a new instance
2 constructor(radius) {
// _radius is a convention for "private" property
3 this._radius = radius;
4 }
// get keyword defines a getter - accessed like a property
5 get radius() {
6 return this._radius;
7 }
// set keyword defines a setter - validates before setting
8 set radius(value) {
// Only set if value is positive
9 if (value > 0) this._radius = value;
10 }
// Computed property that calculates area on access
11 get area() {
// ** is the exponentiation operator (radius squared)
12 return Math.PI * this._radius ** 2;
13 }
14}
// Create a circle with radius 5
15const c = new Circle(5);
// Access area getter and format to 2 decimal places
16console.log(c.area.toFixed(2));

Output

78.54
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
  • (× 8
  • )× 8
  • ;× 6
  • {× 5
  • }× 5
  • _× 4
  • *× 3
  • =× 3
  • >× 1

More JavaScript examples at level 4

← JavaScript typing practice