HomeJAVASCRIPTWhat are getters and setters in JavaScript?

What are getters and setters in JavaScript?

In JavaScript, getters and setters are special methods that allow you to define how properties of an object are accessed (get) and updated (set). They help control and customize access to object properties.


๐Ÿ”น Getter (get)

  • Used to retrieve the value of a property.
  • Defined using the get keyword inside an object or class.
  • Looks like a normal property when accessed, but under the hood, itโ€™s a function.
const person = {
  firstName: "Himanshu",
  lastName: "Sharma",
  
  // Getter
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName);  // "Himanshu Sharma"

๐Ÿ‘‰ Notice: You donโ€™t call it like a function (person.fullName()), you access it like a property (person.fullName).


๐Ÿ”น Setter (set)

  • Used to set/update the value of a property.
  • Defined using the set keyword.
  • Accepts exactly one parameter.
const person = {
  firstName: "Himanshu",
  lastName: "Sharma",
  
  // Getter
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  
  // Setter
  set fullName(name) {
    const parts = name.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

person.fullName = "Rahul Verma";  
console.log(person.firstName);  // "Rahul"
console.log(person.lastName);   // "Verma"

๐Ÿ”น In Classes

You can also use getters and setters in ES6 classes:

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  // Getter
  get area() {
    return this.width * this.height;
  }

  // Setter
  set area(value) {
    this.width = Math.sqrt(value);
    this.height = Math.sqrt(value);
  }
}

const rect = new Rectangle(4, 9);
console.log(rect.area);  // 36  (getter)

rect.area = 49;          // (setter modifies width & height)
console.log(rect.width); // 7
console.log(rect.height);// 7

โœ… Benefits of Getters and Setters

  1. Encapsulation โ†’ Control access to properties.
  2. Validation โ†’ Set rules before assigning values.
  3. Computed Properties โ†’ Dynamically generate values.
  4. Abstraction โ†’ Hide internal implementation.

Share:ย 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *