Getter and Setter in JavaScript

Level 4286 keystrokes

Getters and setters provide controlled access to object properties.

JavaScript code

// Create an object with getters and setters
1const person = {
// Regular properties
2 firstName: "John",
3 lastName: "Doe",
// Getter: computed property accessed like a regular property
4 get fullName() {
5 return `${this.firstName} ${this.lastName}`;
6 },
// Setter: runs when assigning to fullName
7 set fullName(name) {
// Destructure the split name into firstName and lastName
8 [this.firstName, this.lastName] = name.split(" ");
9 }
10};
// Access getter (no parentheses needed)
11console.log(person.fullName);
// Trigger setter
12person.fullName = "Jane Smith";
// Getter now returns updated name
13console.log(person.fullName);

Output

John Doe
Jane Smith
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.

  • .× 10
  • "× 8
  • ;× 6
  • (× 5
  • )× 5
  • {× 5
  • }× 5
  • ,× 4
  • =× 3
  • :× 2

More JavaScript examples at level 4

← JavaScript typing practice