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

What Are Getters and Setters?

Learn how getters and setters allow you to define computed properties with custom get/set logic on objects.

What Are Getters and Setters?

You'll learn how to define special properties on objects that run custom logic whenever you access or modify them.

The Core Idea

Getters and setters are special methods that look like regular properties from the outside, but execute functions behind the scenes. A getter runs when you read a property's value, and a setter runs when you assign a new value to it.

Think of them like smart doorways to your data: instead of directly accessing a storage room, you go through a receptionist who can calculate, validate, or transform information on the way in or out.

Why They're Useful

Getters and setters allow you to:

  • Compute values on-the-fly instead of storing them
  • Validate or transform data before storing it
  • Keep internal properties private while exposing a clean interface
  • Maintain consistency between related properties

How They Look

Unlike regular methods that need () to call, getters and setters are accessed like normal properties:

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

console.log(user.fullName);    // "Jane Doe" (getter runs)
user.fullName = 'John Smith';  // (setter runs)
console.log(user.firstName);   // "John"

Notice: no parentheses! The get and set keywords define these special methods, but they're accessed like properties.

Key Takeaway: Getters and setters let you define computed properties with custom logic that runs automatically when you read or write values, giving you control over how data flows in and out of your objects.