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

Defining Getters with the 'get' Keyword

Use the 'get' keyword in object literals to create properties that execute a function when accessed.

Defining Getters with the 'get' Keyword

You'll learn how to create object properties that run a function automatically whenever you access them.


What is a Getter?

A getter is a special type of object property that looks like a regular property when you access it, but actually executes a function behind the scenes. Instead of storing a value directly, a getter computes or derives a value when you read it.

You define getters using the get keyword in an object literal.

Syntax

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

console.log(person.fullName); // "Jane Doe" — looks like a property!

Notice you access fullName without parentheses. It looks like a regular property, but the function runs automatically.

Why Use Getters?

Getters let you:

  • Compute values on-the-fly instead of storing redundant data
  • Keep your interface clean — users access it like a property, not a method
  • Encapsulate logic — the calculation stays hidden inside the object

Think of a getter as a vending machine slot: you reach in (access the property), and something is prepared for you on demand, rather than sitting there pre-packaged.

Getters vs Regular Methods

const circle = {
  radius: 5,
  
  // Regular method — needs ()
  getArea() {
    return Math.PI * this.radius ** 2;
  },
  
  // Getter — no () needed
  get area() {
    return Math.PI * this.radius ** 2;
  }
};

circle.getArea(); // method call
circle.area;      // getter access — cleaner!

Key Takeaway: Use the get keyword to define properties that execute a function when accessed, making computed values look and feel like regular properties.