Day 65 / 100 Days of Code: Exploring Getters and Setters with Sports
Jacob Stern
Posted on September 5, 2024
Tue, September 3, 2024
Hey everyone! 👋
Today, I wrapped up JavaScript objects, focusing on getters and setters. To keep things interesting, I created a simple sports team object for the Phoenix Suns. Let's have a look!
I started by defining a team object with two main properties: _players and _games. The underscore is a convention to indicate that these properties are meant to be private.
const team = {
_players: [
{firstname: 'Devin', lastname: 'Booker', age: 27},
{firstname: 'Kevin', lastname: 'Durant', age: 35},
{firstname: 'Bradley', lastname: 'Beal', age: 31}
],
_games: [
{opponent: 'Lakers', teampoints: 106, opponentpoints: 99},
{opponent: 'Pistons', teampoints: 120, opponentpoints: 102},
{opponent: 'Nuggets', teampoints: 105, opponentpoints: 104}
]
};
To access the players and games, I used getters. Getters are methods that allow us to read the values of properties without directly accessing them. This keeps our data encapsulated and safe from unintended changes:
get players() {
return this._players;
},
get games() {
return this._games;
}
These getters can be used to retrieve and log the players and games:
console.log(team.players);
console.log(team.games);
Next, we want to be able to add new players and games to the team. For this, I used methods instead of setters. Methods allow us to perform specific actions, like adding new items, without replacing the entire array:
addplayer(newfirstname, newlastname, newage) {
let player = {firstname: newfirstname, lastname: newlastname, age: newage};
this._players.push(player);
},
addgame(newopponent, newteampoints, newopponentpoints) {
let game = {opponent: newopponent, teampoints: newteampoints, opponentpoints: newopponentpoints};
this._games.push(game);
}
To test it out, I added a new player and logged the updated list of players:
team.addplayer('Grayson', 'Allen', 29);
console.log(team.players);
This exercise was a great way to understand how getters and setters work in JavaScript. They provide a clean and efficient way to manage data within objects. Plus, working with a sports team made it more fun!
One detail I miss about my last job is that being a digital ticketing service provider, there were televised sports around the office. This elevated the camaraderie and banter among colleagues, making the work environment lively and engaging. It’s amazing how sports can bring people together, both in the office and in code!
Stay tuned for more updates on my coding journey. Until next time, happy coding! 🚀
Posted on September 5, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.