Setters & Getters in JavaScript and TypeScript - Simple & Code Examples
Setters and getters are important features of object-oriented programming languages like JavaScript and TypeScript. They provide a way to control access to the properties of an object, ensuring that the values are valid and that the object is in a consistent state. In this blog post, I will provide an overview of setters and getters and how they work in JavaScript and TypeScript. I will also provide code examples in both languages to illustrate how setters and getters can be used with local storage.
Overview
Setters and getters are methods that are used to get and set the values of the properties of an object.
A getter is a method that retrieves the value of a property, while a setter is a method that sets the value of a property.
Setters and getters are used to enforce data encapsulation, ensuring that the internal state of an object is protected and not exposed to external code. They can also be used to add custom logic to the object when a property is set or retrieved.
Benefits of using setters and getters include:
Controlling access to object properties
Enforcing data encapsulation
Adding custom logic to object properties
Code Examples
In the following code examples, we demonstrate how to use setters and getters with localStorage
in JavaScript. localStorage
is a browser feature that allows developers to store key-value pairs in a user's browser, which can be accessed across multiple sessions or even on different devices.
JavaScript Example
class User {
constructor(name, email) {
this._name = name;
this._email = email;
}
get name() {
return this._name;
}
set name(value) {
localStorage.setItem('name', value);
this._name = value;
}
get email() {
return this._email;
}
set email(value) {
localStorage.setItem('email', value);
this._email = value;
}
}
let user = new User(localStorage.getItem('name'), localStorage.getItem('email'));
console.log(user.name); // Output: "Esther White"
user.name = "Jane Smith"; // Set the name property and store it in local storage
log(localStorage.getItem('name')); // Output: "Jane Smith"
In this example, we create a User
class with name
and email
properties. We define getters and setters for each property. When a setter is called, we store the new value in local storage. When a getter is called, we return the value from the corresponding property. We also create a new User
object and set its name
and email
properties to the values stored in local storage. We then log the value of user.name
to the console, which outputs "John Doe". We set the name
property of the user
object to "Jane Smith" and log its value to the console, which outputs "Jane Smith". We also log the value of localStorage.getItem('name')
to the console, which outputs "Jane Smith".
TypeScript Example
class User {
private _name: string;
private _email: string;
constructor(name: string, email: string) {
this._name = name;
this._email = email;
}
get name(): string {
return this._name;
}
set name(value: string) {
localStorage.setItem('name', value);
this._name = value;
}
get email(): string {
return this._email;
}
set email(value: string) {
localStorage.setItem('email', value);
this._email = value;
}
}
let user = new User(localStorage.getItem('name'), localStorage.getItem('email'));
console.log(user.name); // Output: "Esther White"
user.name = "Jane Smith"; // Set the name property and store it in local storage
console.log(user.name); // Output: "Jane Smith"
console.log(localStorage.getItem('name')); // Output: "Jane Smith"
This TypeScript code is similar to the JavaScript code, but with additional type annotations for the User
class and its properties. We define name
and email
properties with getters and setters, just like in the JavaScript example. We then create a new User
object and set its name
and email
properties to the values stored in local storage. We log the value of user.name
to the console, which outputs "John Doe". We set the name
property of the user
object to "Jane Smith" and log its value to the console, which outputs "Jane Smith". We also log the value of localStorage.getItem('name')
to the console, which outputs "Jane Smith". By using getters and setters with local storage, we can store and retrieve data in a consistent and reliable way, making our code more maintainable and easier to read.
Local Storage - setItem and getItem
localStorage.setItem()
and localStorage.getItem()
are functions that behave as setters and getters for the localStorage
object in JavaScript.
localStorage.setItem(key, value)
sets the value of an item in the localStorage
object with the specified key
and value
parameters, and localStorage.getItem(key)
retrieves the value of an item from the localStorage
object with the specified key
parameter. These functions abstract away the details of how localStorage
is actually implemented, allowing developers to interact with it in a simplified manner through a high-level API.
In a way, localStorage
itself can be considered an abstraction, as it provides a higher-level interface to the browser's underlying storage mechanisms, which may differ between different browsers and operating systems.
Conclusion
Setters and getters are important features of object-oriented programming languages like JavaScript and TypeScript. They provide a way to control access to the properties of an object, ensuring that the values are valid and that the object is in a consistent state. Setters and getters are used to enforce data encapsulation, ensuring that the internal state of an object is protected and not exposed to external code. They can also be used to add custom logic to the object when a property is set or retrieved. In this blog post, we provided an overview of setters and getters and how they work in JavaScript and TypeScript. We also provided code examples in both languages to illustrate how setters and getters can be used with a mobile phone object. By using setters and getters, you can ensure that your objects are always in a valid and consistent state, making your code more reliable and easier to maintain.