DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Getters And Setters: What Are Getters And Setters In JavaScriptΒ ?
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’»

Posted on • Originally published at Medium

Getters And Setters: What Are Getters And Setters In JavaScriptΒ ?

Introduction:

image of numbers on a dice

Programmers use getters and setters frequently, and we see them in code. If you are having a hard time understanding getters and setters, I will try to explain it so you could understand.
In this article, we are going to look at getters and setters, what they are, and object.defineproperty().

What are Getters AndΒ Setters:

Getters and setters are functions that are used to access values.
Getters and setters are called accessor properties. There are two kinds of object properties in JavaScript: data properties and accessor properties.Β 
We normally use data properties in objects. For example,

const names = {
    myName: 'Ezinne';
};
Enter fullscreen mode Exit fullscreen mode

The above code is an example of a data property. It takes in data and would give an output if console.log is used.

Getters and setters can take in data and also access or manipulate the values of that data. They differ from each other as their use cases are different.

Getters can get, as the name implies, the value of a property. In the example code shared above, we could use a getter to get the value of the variable myName. Here's an example:

const  names = {
    myName: 'Ezinne',

    //using get to access the value
    get getmyName() {
        return this.myName;
    }
};
console.log(names.getmyName);
Enter fullscreen mode Exit fullscreen mode

Now, we could retrieve the value of the names object by console logging the getter method.

Note: we could use any other name apart from getmyName.

Let's look at another example.

const topics = {
    arrays: "reduce",
    objects: "literals",

    get someTopics() {
        return `${this.arrays} ${this.objects}`;
    }
};
console.log(topics.someTopics);
Enter fullscreen mode Exit fullscreen mode

In this example, the getter is used to read two values. You could add more values. But you cannot assign a new value to it as getters take zero parameters. This is where the setter comes in.
Β 
Setters are defined simply as a method that could set or change a value. It takes a parameter, which is the change expected.Β 
If we wanted to assign a new name to our myName variable in the first example, we would have to use a setter.

const  names = {
  myName: 'Ezinne',
//using get to access the value
get getmyName() {
  return this.myName;
},
//using set to change the value
set changeMyName(newName) {
  this.myName = newName;
 }
};
console.log(names.getmyName);
names.changeMyName = 'Anna';
console.log(names.myName);
Enter fullscreen mode Exit fullscreen mode

Definition of Object.Define Property

This is a property that is used to add getters and setters.

This is the syntax:
Object.defineProperty(obj, prop, descriptor)

To apply Object.defineProperty in the previous examples,

const topics = {
  arrays: "reduce",
  objects: "literals",
};

Object.defineProperty(topics, 'someTopics', {
  get () {
    return `${this.arrays} ${this.objects}`;
  },
});

Object.defineProperty(topics, 'otherTopics', {
  set (otherTopics) {
    [this.arrays, this.objects] = otherTopics;
 }
});

console.log(topics.someTopics);
topics.otherTopics = ['variables','symbols'];
console.log(topics.arrays);
console.log(topics.objects);
Enter fullscreen mode Exit fullscreen mode

In Object.defineProperty, when we use a getter, it does not use a name like getTopics and a setter takes only the parameter as we could see from the example.

The Object.defineProperty takes three arguments;
The first argument is the name of the object. In our example, it is topics. The second argument is the name of the property, which is someTopics and the third argument is a description. This contains the getters and setters used in this case.

Another Example

const game = {
  player1: "dreadking",
  player2: "invincible",
};

Object.defineProperty(game, 'players', {
  get () {
    return `${this.player1} ${this.player2}`
  },
});

Object.defineProperty(game, "new Players", {
  set (newPlayers) {
    [this.player1,this.player2] = [newPlayers];
  }
});

console.log(game.players)
game.newPlayers = ['tigerarrow', 'fiercely'];
console.log(`new player: ${game.player1}`);
console.log(`new player: ${game.player2}`);
Enter fullscreen mode Exit fullscreen mode

In this example, we are writing a simple game application that returns the name of the players in the game by logging it to the console using getters. Using setters, we are able to change the names of those players and log it to the console as well.

Why Do We Use Getters andΒ Setters?

  • We use getters and setters to access object properties.

  • We use getters and setters when we want to add more logic to our code.

  • In Object-Oriented Programming (OOP), we use them for encapsulation, to hide complexity in our code.

Conclusion

Now, we have learned getters and setters, Object.defineProperty and when to use them. Also, did some exercises so our brain could apply some cognitive effort in understanding the topic.

Thank you for reading and Cheers to more learning

Top comments (2)

Collapse
parenttobias profile image
Toby Parent

This is excellent! I appreciate a good in-depth exploration of how getters and setters can be useful. Another neat advantage to them? When we JSON.stringify() our objects, whether constructors or factories, the functions in them are stripped away. But getters are not treated as functions, but as their returned type.

Collapse
ezinne_anne profile image
Ezinne AnneπŸ˜ŽπŸ‘©πŸΏβ€πŸ’» Author

Yes, thank you for reading

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.