Getters in Classes
When you want to control how a property is accessed in a class, you can use a getter method. Getters allow you to define special methods that are accessed like properties, using the get keyword. This lets you compute a value, validate data, or even hide internal implementation details, all while letting users of your class interact with the property as if it were a regular field. With getters, you can make your classes safer and more flexible by controlling what happens when someone tries to read a property.
12345678910111213class Product { constructor(name, priceCents) { this.name = name; this._priceCents = priceCents; } get price() { return (this._priceCents / 100).toFixed(2); } } const item = new Product("Headphones", 2599); console.log(item.price); // "25.99"
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 6.25
Getters in Classes
Swipe to show menu
When you want to control how a property is accessed in a class, you can use a getter method. Getters allow you to define special methods that are accessed like properties, using the get keyword. This lets you compute a value, validate data, or even hide internal implementation details, all while letting users of your class interact with the property as if it were a regular field. With getters, you can make your classes safer and more flexible by controlling what happens when someone tries to read a property.
12345678910111213class Product { constructor(name, priceCents) { this.name = name; this._priceCents = priceCents; } get price() { return (this._priceCents / 100).toFixed(2); } } const item = new Product("Headphones", 2599); console.log(item.price); // "25.99"
Thanks for your feedback!