JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Get/Set


In JavaScript, getters and setters are special methods that allow controlled access to object properties. They are part of JavaScript’s object-oriented features and help manage data encapsulation, validation, and dynamic computation of values.

  • Getter: A method that retrieves a property value when the property is accessed.

  • Setter: A method that updates a property value when a new value is assigned.

Using getters and setters ensures that data is accessed or modified safely, reducing potential bugs or invalid state changes. They are widely used in complex applications, API response handling, and modern frameworks.

1. Basic Getter

A getter allows a property to be accessed like a normal property while actually calling a function behind the scenes.

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

console.log(person.fullName); // John Doe
  • fullName is accessed without parentheses.

  • Getters are useful when a value is derived from other properties, for example, combining firstName and lastName.

Notes on Getters

  • Getters can help compute values dynamically without storing extra data.

  • They improve readability by exposing a property-like interface for computed values.

2. Basic Setter

A setter allows you to execute logic when a property value is updated.

const person = {
  firstName: "John",
  lastName: "Doe",
  set fullName(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

person.fullName = "Alice Smith";
console.log(person.firstName); // Alice
console.log(person.lastName);  // Smith
  • The setter receives a single argument representing the new value.

  • Inside the setter, you can split, validate, transform, or modify values before storing them.

3. Getters and Setters Together

Objects can have both a getter and a setter for the same property, allowing controlled read/write access.

const person = {
  firstName: "John",
  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(person.fullName); // John Doe
person.fullName = "Alice Smith";
console.log(person.fullName); // Alice Smith
  • Getters and setters can encapsulate logic, ensuring internal properties remain consistent.

4. Using Object.defineProperty()

JavaScript provides Object.defineProperty() to define getters and setters with more control over property behavior.

const person = { firstName: "John", lastName: "Doe" };

Object.defineProperty(person, "fullName", {
  get() {
    return `${this.firstName} ${this.lastName}`;
  },
  set(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  },
  enumerable: true,
  configurable: true
});

console.log(person.fullName); // John Doe
person.fullName = "Alice Smith";
console.log(person.firstName); // Alice
console.log(person.lastName);  // Smith
  • enumerable: true ensures the property shows up in loops or Object.keys().

  • configurable: true allows redefining or deleting the property later.

  • Object.defineProperty() is ideal for precise control, such as creating read-only or computed properties.

5. Validation Using Setters

Setters are ideal for validating input before updating a property.

const student = {
  _age: 18, // underscore indicates internal/private-like property
  get age() {
    return this._age;
  },
  set age(value) {
    if (value < 0) {
      console.log("Age cannot be negative");
    } else {
      this._age = value;
    }
  }
};

student.age = 20;
console.log(student.age); // 20
student.age = -5;         // Age cannot be negative
  • The internal _age property prevents infinite recursion inside the setter.

  • This technique is widely used for data integrity and encapsulation.

6. Computed Properties Using Getters

Getters allow dynamic computation without storing additional values.

const rectangle = {
  width: 10,
  height: 5,
  get area() {
    return this.width * this.height;
  }
};

console.log(rectangle.area); // 50
  • area is computed on demand.

  • Avoid heavy computations in getters to prevent performance issues.

7. Best Practices

  1. Use getters for derived values: For example, full names, totals, or computed fields.

  2. Use setters for validation: Ensure data integrity before updating values.

  3. Avoid heavy computation in getters: Keep them lightweight.

  4. Use underscores for private-like properties: Helps prevent recursion in setters.

  5. Consider Object.defineProperty() for advanced control over enumerability, configurability, or writability.

8. Advantages of Getters and Setters

  • Provide controlled access to object properties.

  • Ensure data validation before assignment.

  • Enable computed or derived properties without storing extra data.

  • Encapsulate business logic within objects, improving readability and maintainability.

  • Essential for building robust applications with predictable behavior.

9. Summary of the Tutorial

  • Getters are used to read properties dynamically.

  • Setters are used to modify properties with control and validation.

  • They can be defined directly in object literals or via Object.defineProperty().

  • Proper use of getters and setters ensures data integrity, encapsulation, and maintainable code.

  • They are a key concept for modern JavaScript development and object-oriented programming.

Mastering getters and setters is critical for any JavaScript developer, as they form the foundation for encapsulation, computed properties, and safe property updates in both simple scripts and complex applications.


Practice Questions

  1. Basic Getter
    Create an object person with firstName and lastName. Define a getter fullName that returns the full name. Access and log fullName.

  2. Basic Setter
    Add a setter fullName to the same object that splits a string and updates firstName and lastName. Test it by assigning a new name.

  3. Getter and Setter Together
    Create an object student with firstName, lastName, and a fullName getter/setter. Access the full name, then update it via the setter, and log all properties.

  4. Validation with Setter
    Create a student object with a private-like property _age. Add a setter age that prevents negative values. Test it with valid and invalid numbers.

  5. Computed Property
    Create a rectangle object with width and height. Define a getter area that computes the area dynamically. Log the computed area.

  6. Object.defineProperty() Getter/Setter
    Use Object.defineProperty() to define a property fullName with getter and setter for a person object. Test reading and updating the property.

  7. Dynamic Update via Setter
    Create an object employee with a setter for salary that ensures the salary cannot be below 1000. Test updating the salary.

  8. Private-like Property Access
    Create an object account with _balance. Add a getter and setter to safely access and update _balance. Log the updates.

  9. Chained Setter Update
    Create a setter for temperature in a weather object that converts Celsius to Fahrenheit internally and updates another property. Test the behavior.

  10. Full Name Transformation
    Create an object user with firstName and lastName. Use a setter to update fullName but automatically capitalize the first letters of both names. Log the result.

Do you want me to do that next?


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top