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 setters1const person = { // Regular properties2 firstName: "John",3 lastName: "Doe", // Getter: computed property accessed like a regular property4 get fullName() {5 return `${this.firstName} ${this.lastName}`;6 }, // Setter: runs when assigning to fullName7 set fullName(name) { // Destructure the split name into firstName and lastName8 [this.firstName, this.lastName] = name.split(" ");9 }10};// Access getter (no parentheses needed)11console.log(person.fullName);// Trigger setter12person.fullName = "Jane Smith";// Getter now returns updated name13console.log(person.fullName);Output
John Doe Jane Smith
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