JavaScript getters and setters are special methods that allow you to control how an object’s properties are accessed and updated. A getter runs when you read a property, while a setter runs when you assign a value to a property.
Getters and setters are commonly used with JavaScript classes to calculate values, validate data, and control how properties are modified.
For example, you can use a setter to prevent a product from having a negative price or a getter to return a person’s full name from their first and last names.
In this tutorial, you will learn how getters and setters work, how to define them inside a class, how to validate values, and how they differ from regular methods.
What Are Getters and Setters in JavaScript?
Getters and setters are special methods defined using the get and set keywords.
- Getter: Retrieves or calculates a value when a property is accessed.
- Setter: Runs when a value is assigned to a property and allows you to control how that value is stored.
Although they are defined as methods, getters and setters are accessed like properties rather than called with parentheses.
Basic Example
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value;
}
}
const user = new User("Rahul");
console.log(user.name);
user.name = "Priya";
console.log(user.name);
Output:
Rahul
Priya
In this example:
get name()defines a getter.set name(value)defines a setter.user.namereads the property and triggers the getter.user.name = "Priya"assigns a value and triggers the setter.
Notice that neither user.name nor user.name = "Priya" uses parentheses. JavaScript invokes the corresponding accessor automatically.
To understand the structure used in this example, explore JavaScript Classes.
Getters in JavaScript
A getter is a special method that runs when you access a property. It can return a stored value or calculate a value from other properties.
Getter Syntax
class ClassName {
get propertyName() {
return this._propertyName;
}
}
The get keyword defines the getter. The getter can return a value whenever the property is accessed.
Example of a Getter
class Student {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
}
const student = new Student("Ayesha");
console.log(student.name);
Output:
Ayesha
When JavaScript evaluates student.name, it runs the getter and returns the value stored in _name.
You access the getter as a property, not as a regular function.
Incorrect:
// student.name() would cause a TypeError
Correct:
console.log(student.name);
Using a Getter to Calculate a Value
A getter does not have to return a property stored directly in the object. It can calculate a result from other properties.
class Rectangle {
constructor(length, width) {
this.length = length;
this.width = width;
}
get area() {
return this.length * this.width;
}
}
const rectangle = new Rectangle(10, 5);
console.log(rectangle.area);
Output:
50
The area getter calculates the rectangle’s area using its length and width.
You do not need to call rectangle.area() because area behaves like a property.
If the dimensions change, the next access to area calculates the result using the updated values.
rectangle.length = 20;
console.log(rectangle.area);
Output:
100
This is useful when you want a property-like interface for a value that depends on other data.
Setters in JavaScript
A setter is a special method that runs when you assign a value to a property. It lets you control how the new value is handled.
Setters are useful for validating input, transforming values, and keeping an object’s data consistent.
Setter Syntax
class ClassName {
set propertyName(value) {
// Process or validate the value
}
}
The set keyword defines the setter. It accepts exactly one parameter, which receives the assigned value.
Example of a Setter
class User {
set name(value) {
this._name = value;
}
get name() {
return this._name;
}
}
const user = new User();
user.name = "Rahul";
console.log(user.name);
Output:
Rahul
When you assign "Rahul" to user.name, JavaScript invokes the setter. The setter stores the value in _name.
When you read user.name, the getter returns the stored value.
Why Use a Setter?
Without a setter, you might assign values directly without checking whether they are valid. A setter lets you apply rules before accepting a value.
For example, a product price should not be negative.
class Product {
constructor(price) {
this.price = price;
}
get price() {
return this._price;
}
set price(value) {
if (value >= 0) {
this._price = value;
} else {
console.log("Price cannot be negative.");
}
}
}
const product = new Product(1000);
console.log(product.price);
product.price = -500;
console.log(product.price);
Output:
1000
Price cannot be negative.
1000
When the object is created, the constructor assigns the initial price through the setter. The setter accepts 1000 because it is valid.
When -500 is assigned, the setter rejects it and leaves the previous value unchanged.
For production applications, you might prefer throwing an error or returning validation results instead of only displaying a message.
Using Getters and Setters Together
Getters and setters are often used together to provide controlled access to a property’s value.
The getter reads the value, while the setter processes new values before storing them.
Example: Managing a Student’s Marks
class Student {
constructor(marks) {
this.marks = marks;
}
get marks() {
return this._marks;
}
set marks(value) {
if (value >= 0 && value <= 100) {
this._marks = value;
} else {
console.log("Marks must be between 0 and 100.");
}
}
}
const student = new Student(85);
console.log(student.marks);
student.marks = 95;
console.log(student.marks);
student.marks = 120;
console.log(student.marks);
Output:
85
95
Marks must be between 0 and 100.
95
The setter accepts marks only when the value is between 0 and 100. The getter provides access to the accepted value.
This example demonstrates how accessors can help maintain simple validation rules inside a class.
Using Getters to Combine Properties
Getters can calculate values from multiple properties and present them as a single property.
For example, you can combine a person’s first name and last name into a full name.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const person = new Person("Rahul", "Kumar");
console.log(person.fullName);
Output:
Rahul Kumar
The fullName getter combines the two properties whenever you access it.
There is no need to store fullName separately if it can be calculated from firstName and lastName.
If either name changes, the getter reflects the updated values automatically.
Using Setters to Transform Values
A setter can modify a value before storing it. For example, you can convert a username to lowercase to keep its format consistent.
class User {
constructor(username) {
this.username = username;
}
get username() {
return this._username;
}
set username(value) {
this._username = value.trim().toLowerCase();
}
}
const user = new User(" RAHUL123 ");
console.log(user.username);
Output:
rahul123
The setter removes leading and trailing whitespace using trim() and converts the value to lowercase.
This example assumes that the assigned value is a string. If the input can come from untrusted or unpredictable sources, validate its type before calling string methods.
Getters and Setters vs Regular Methods
Getters, setters, and regular methods all use functions internally, but they are accessed differently.
| Feature | Getter | Setter | Regular Method |
|---|---|---|---|
| Purpose | Reads or calculates a value | Processes an assigned value | Performs an operation |
| Keyword | get | set | No special keyword |
| How it is used | object.property | object.property = value | object.method() |
| Parameters | No parameters | Exactly one parameter | Can accept parameters |
| Return value | Returns the accessed value | Its return value is ignored by ordinary assignment | Can return a value |
Example Comparing All Three
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
get celsius() {
return this._celsius;
}
set celsius(value) {
this._celsius = value;
}
toFahrenheit() {
return (this._celsius * 9 / 5) + 32;
}
}
const temperature = new Temperature(25);
console.log(temperature.celsius);
temperature.celsius = 30;
console.log(temperature.toFahrenheit());
Output:
25
86
The getter reads the Celsius value, the setter updates it, and the regular method converts the current value to Fahrenheit.
Important Rules for Getters and Setters
A Getter Cannot Accept Parameters
A getter must not have parameters.
Correct:
get name() {
return this._name;
}
Incorrect:
// SyntaxError: a getter cannot have parameters
// get name(value) { return value; }
A Setter Must Accept Exactly One Parameter
A setter must have one parameter to receive the assigned value.
Correct:
set name(value) {
this._name = value;
}
A setter cannot declare zero or multiple parameters.
Avoid Infinite Recursion
One common mistake is assigning a value to the same property inside its setter.
Incorrect:
class User {
set name(value) {
this.name = value;
}
}
This setter assigns to name, which triggers the same setter again, causing repeated calls until a stack overflow occurs.
Use a different backing property instead:
class User {
set name(value) {
this._name = value;
}
get name() {
return this._name;
}
}
const user = new User();
user.name = "Priya";
console.log(user.name);
Output:
Priya
The _name property stores the value without invoking the name setter again. The underscore is a naming convention, not a privacy feature.
Getters and Setters Are Not Automatically Validation Systems
A setter only validates data if you write the validation logic yourself. Without that logic, it may simply store any value.
For more robust applications, consider the expected data type, permitted range, and how invalid values should be handled.
Frequently Asked Questions
What is a getter in JavaScript?
A getter is a special method that runs when a property is accessed. It can return a stored value or calculate one from other properties.
What is a setter in JavaScript?
A setter is a special method that runs when a value is assigned to a property. It can validate, transform, or store the assigned value.
Why are getters and setters useful?
They provide property-like access while allowing you to calculate values, validate input, and control how data is updated.
Do getters and setters require the get and set keywords?
Yes. These keywords identify accessor methods in a class or object definition.
Can a getter have parameters?
No. A getter cannot declare parameters. A setter must declare exactly one parameter.
Are getters and setters available outside classes?
Yes. JavaScript also supports getters and setters in object literals and through property descriptors. Classes are simply one common way to define them.
Conclusion
JavaScript getters and setters provide controlled, property-like access to object data. Getters retrieve or calculate values, while setters process assigned values before storing them.
They are especially useful for validation, data transformation, and calculated properties. By using them correctly, you can make your JavaScript classes easier to use and maintain.