JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Object Accessors

14 April 2025 | Category:

Object accessors allow you to control how properties are accessed and modified in JavaScript. They provide a way to define computed or protected properties using special methods called getters and setters.


🧠 Why Use Accessors?

Accessors are useful when you:

  • Want to control or customize property access
  • Need to compute a value on the fly
  • Want to validate or restrict data updates

đŸ“„ Getters

A getter is a method that is called when you try to access a property.

đŸ§Ș Syntax:

const obj = {
  get propName() {
    // logic here
    return value;
  }
};

đŸ§© Example:

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

console.log(person.fullName); // Jane Smith

✅ Note: You access it like a property, not a function (person.fullName, not person.fullName()).


đŸ“€ Setters

A setter is a method that is called when a property value is assigned.

đŸ§Ș Syntax:

const obj = {
  set propName(value) {
    // logic here
  }
};

đŸ§© Example:

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

user.fullName = "Alice Cooper";
console.log(user.firstName); // Alice
console.log(user.lastName);  // Cooper

🔄 Full Example with Getter and Setter

const product = {
  _price: 0,
  get price() {
    return `$${this._price.toFixed(2)}`;
  },
  set price(value) {
    if (value < 0) {
      console.error("Price must be positive");
    } else {
      this._price = value;
    }
  }
};

product.price = 25.5;
console.log(product.price); // $25.50

📝 Note:

  • Prefix like _price is often used to represent the private version of a property.

🔎 Advantages of Using Accessors

  • Encapsulation: Hide internal implementation
  • Validation: Validate values before setting
  • Read-only/Write-only: Control access to sensitive data
  • Computed Properties: Return dynamic values

❌ Caution

  • Getters must return a value, or you’ll get undefined.
  • Avoid heavy logic in accessors to keep performance fast.
  • Don’t make accessors do unexpected things (like modifying unrelated data).

🧠 Bonus: Define Accessors with Object.defineProperty()

const student = { name: "Tom" };

Object.defineProperty(student, "greeting", {
  get() {
    return `Hello, ${this.name}`;
  }
});

console.log(student.greeting); // Hello, Tom