About Lesson
JavaScript Getters and Setters
-
Encapsulation: Getters and setters are used to encapsulate data within an object, providing more control over how that data is accessed and modified.
-
Getters:
-
Used to retrieve the value of a property.
-
Defined using the
get
keyword before the property name. -
Example:
JavaScriptclass Person { constructor(firstName) { this._firstName = firstName; // Private property } get firstName() { return this._firstName; } }
-
-
Setters:
-
Used to set the value of a property.
-
Defined using the
set
keyword before the property name. -
Example:
JavaScriptclass Person { constructor(firstName) { this._firstName = firstName; // Private property } get firstName() { return this._firstName; } set firstName(value) { if (typeof value !== 'string') { throw new Error("First name must be a string"); } this._firstName = value; } }
-
-
Benefits:
- Data Validation: Enforce data integrity by performing checks within the setter.
- Data Transformation: Perform transformations on the data before setting the property value.
- Read-Only Properties: Create read-only properties by defining a getter but no setter.
- Improved Maintainability: Encapsulating data makes your code more maintainable and easier to modify.
-
Example Usage:
JavaScriptconst person = new Person("John"); console.log(person.firstName); // Accessing the value using the getter person.firstName = "Jane"; // Setting the value using the setter
Getters and setters are valuable tools for creating well-structured and maintainable JavaScript objects, promoting data integrity and improving code quality.