Course contentsShow
← JavaScript
Lesson 661 of 2,72316. Object Methods and PatternsFree lesson

Getters Return Values, Setters Accept One Parameter

Understand that getters must return a value and setters receive exactly one argument representing the new value.

Getters Return Values, Setters Accept One Parameter

You'll learn the essential rules that govern what getters and setters do with data.

Now that you know how to define getters and setters using the get and set keywords, let's clarify their fundamental contracts: what they must do and what they receive.

The Getter Contract: Always Return Something

A getter is like a window into your object. When someone accesses a property via a getter, they expect to receive a value back. Your getter must return something—even if it's undefined or null. Without a return statement, your getter returns undefined by default, which may not be what you intended.

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(user.fullName); // "Jane Doe" — getter returns a value

The Setter Contract: Accept Exactly One Parameter

A setter is like a door that accepts deliveries. It receives exactly one parameter: the new value being assigned. JavaScript enforces this—even if you write multiple parameters, only the first one will be passed when the property is assigned.

const user = {
  firstName: 'Jane',
  lastName: 'Doe',
  
  set fullName(name) {
    const parts = name.split(' ');
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

user.fullName = 'John Smith'; // setter receives "John Smith" as the single parameter
console.log(user.firstName); // "John"

Think of it this way: getters are questions (they answer with a value), and setters are instructions (they receive one piece of data to process).

Key Takeaway: Getters must return a value to be useful; setters accept exactly one parameter representing the new value being assigned to that property.