Difference between this and the traditional method?

Weren’t we able to achieve, what getter and setter functions achieve here, earlier as well via simpler methods like :

object_name.property //returns the value of the property
object.property = “New_Value” //modifies the value

Then what is the purpose of using getter setter ??

Your code so far

class Book {
  constructor(author) {
    this._author = author;
  // getter
  get writer() {
    return this._author;
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
const novel = new Book('anonymous');
novel.writer = 'newAuthor';

**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36</code>

**Challenge:**  Use getters and setters to Control Access to an Object

**Link to the challenge:**

It’s a function, so you can do things like validate the value, or transform it in some way, or anything else you might need to do with the value.

Since nothing like that is happening in the sample you posted, I understand your confusion.


So basically what you mean is it is useful for further complex actions rather than just get a value or set a value which can be done easily the other way I have mentioned?
Correct me if I am wrong.

That’s correct.

Here’s another contrived example, but imagine we have a Circle object and pass its radius to the constructor.

class Circle {
  constructor(radius) {
    this.radius = radius;

Now we can add a getter for the area, which is calculated using the radius property.

get area() {
  return Math.PI * this.radius * this.radius;

This is one use case for a getter, derived properties.


Thanks a lot :slight_smile: , I understand the concept now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.