In this chapter, we will learn about JavaScript getters and setters. Getters and setters allow you to define methods that are executed when a property is accessed or modified. We will cover:
- What are Getters and Setters?
- Creating Getters and Setters
- Using Getters and Setters
- Advantages of Getters and Setters
- Simple Programs using Getters and Setters
What are Getters and Setters?
Getters and setters are special methods in JavaScript that allow you to define custom behavior for when a property is accessed (getter) or modified (setter). They provide a way to intercept property access and assignment, making it possible to add custom logic and validation.
Creating Getters and Setters
You can create getters and setters using the get
and set
keywords within a class or an object.
Syntax
class ClassName { constructor(parameters) { // Initialize properties } // Getter get propertyName() { // Return a value } // Setter set propertyName(value) { // Modify a value } }
Example
class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // Getter for full name get fullName() { return `${this.firstName} ${this.lastName}`; } // Setter for full name set fullName(name) { let parts = name.split(' '); this.firstName = parts[0]; this.lastName = parts[1]; } }
Using Getters and Setters
Getters and setters are accessed like regular properties.
Example
let person = new Person("Ramesh", "Fadatare"); console.log(person.fullName); // Using the getter person.fullName = "Neha Sharma"; // Using the setter console.log(person.firstName); console.log(person.lastName);
Output:
Ramesh Fadatare Neha Sharma
Advantages of Getters and Setters
- Encapsulation: Getters and setters provide a way to encapsulate the internal representation of data, allowing you to control access and modification.
- Validation: You can add validation logic within setters to ensure that data meets certain criteria before being assigned.
- Computed Properties: Getters allow you to create computed properties that are derived from other properties.
Simple Programs using Getters and Setters
Program 1: Temperature Conversion
class Temperature { constructor(celsius) { this.celsius = celsius; } // Getter for Fahrenheit get fahrenheit() { return this.celsius * 9/5 + 32; } // Setter for Fahrenheit set fahrenheit(value) { this.celsius = (value - 32) * 5/9; } } let temp = new Temperature(25); console.log("Celsius:", temp.celsius); console.log("Fahrenheit:", temp.fahrenheit); temp.fahrenheit = 100; console.log("Celsius after setting Fahrenheit:", temp.celsius);
Output:
Celsius: 25 Fahrenheit: 77 Celsius after setting Fahrenheit: 37.77777777777778
Program 2: Rectangle Area and Perimeter
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } // Getter for area get area() { return this.width * this.height; } // Getter for perimeter get perimeter() { return 2 * (this.width + this.height); } } let rect = new Rectangle(10, 5); console.log("Width:", rect.width); console.log("Height:", rect.height); console.log("Area:", rect.area); console.log("Perimeter:", rect.perimeter);
Output:
Width: 10 Height: 5 Area: 50 Perimeter: 30
Program 3: Bank Account Balance
class BankAccount { constructor(balance) { this._balance = balance; } // Getter for balance get balance() { return this._balance; } // Setter for balance with validation set balance(amount) { if (amount < 0) { console.log("Balance cannot be negative."); } else { this._balance = amount; } } } let account = new BankAccount(1000); console.log("Initial Balance:", account.balance); account.balance = 2000; console.log("Updated Balance:", account.balance); account.balance = -500; // This should trigger validation
Output:
Initial Balance: 1000 Updated Balance: 2000 Balance cannot be negative.
Program 4: Inventory Management
class Inventory { constructor() { this._items = []; } // Getter for items get items() { return this._items; } // Setter for items with validation set items(newItems) { if (Array.isArray(newItems)) { this._items = newItems; } else { console.log("Items should be an array."); } } } let inventory = new Inventory(); console.log("Initial Items:", inventory.items); inventory.items = ["item1", "item2"]; console.log("Updated Items:", inventory.items); inventory.items = "item3"; // This should trigger validation
Output:
Initial Items: [] Updated Items: [ 'item1', 'item2' ] Items should be an array.
Program 5: Student Grades
class Student { constructor(name, grades) { this.name = name; this._grades = grades; } // Getter for grades get grades() { return this._grades; } // Setter for grades with validation set grades(newGrades) { if (newGrades.every(grade => grade >= 0 && grade <= 100)) { this._grades = newGrades; } else { console.log("All grades should be between 0 and 100."); } } // Getter for average grade get averageGrade() { let sum = this._grades.reduce((acc, grade) => acc + grade, 0); return sum / this._grades.length; } } let student = new Student("Priya", [85, 90, 78]); console.log("Initial Grades:", student.grades); console.log("Average Grade:", student.averageGrade); student.grades = [88, 92, 80]; console.log("Updated Grades:", student.grades); console.log("New Average Grade:", student.averageGrade); student.grades = [105, 90, 78]; // This should trigger validation
Output:
Initial Grades: [ 85, 90, 78 ] Average Grade: 84.33333333333333 Updated Grades: [ 88, 92, 80 ] New Average Grade: 86.66666666666667 All grades should be between 0 and 100.
Conclusion
In this chapter, you learned about JavaScript getters and setters, including how to create and use them. We also discussed the advantages of using getters and setters and provided various use cases with simple programs to demonstrate their usage. Getters and setters are powerful tools for encapsulating and validating data in your classes.