๐Ÿ”ง JavaScript get and set

โœ… What are Getters and Setters?

  • Getter (get): Returns the value of a property.
  • Setter (set): Sets or updates the value of a property.

They are defined inside objects and are used like regular properties, but work like functions behind the scenes.


๐Ÿ“Œ 1. Basic get Example

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

console.log(person.fullName); // John Doe

๐Ÿ” You access fullName like a property, but it’s actually a method using get.


๐Ÿ“Œ 2. Basic set Example

jsCopyEditconst person = {
  firstName: "John",
  lastName: "Doe",
  set fullName(name) {
    const [first, last] = name.split(" ");
    this.firstName = first;
    this.lastName = last;
  }
};

person.fullName = "Jane Smith";
console.log(person.firstName); // Jane
console.log(person.lastName);  // Smith

โš ๏ธ set must accept exactly one parameter.


๐Ÿ“Œ 3. Combining get and set

jsCopyEditconst user = {
  firstName: "Alice",
  lastName: "Brown",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  set fullName(value) {
    const parts = value.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1] || "";
  }
};

console.log(user.fullName); // Alice Brown
user.fullName = "Emily Davis";
console.log(user.fullName); // Emily Davis

๐Ÿ“Œ 4. Why Use Getters and Setters?

Use CaseBenefit
EncapsulationHide internal structure
Input validationCheck/set only valid values
Computed propertiesReturn derived values dynamically
Logging/debuggingAdd logs every time a property is accessed or set

๐Ÿ“Œ 5. Example: With Validation

jsCopyEditconst account = {
  _balance: 1000,
  get balance() {
    return this._balance;
  },
  set balance(amount) {
    if (amount < 0) {
      console.log("Invalid amount");
      return;
    }
    this._balance = amount;
  }
};

console.log(account.balance); // 1000
account.balance = -500;       // Invalid amount
console.log(account.balance); // 1000
account.balance = 2000;
console.log(account.balance); // 2000

๐Ÿ” Convention: use _ prefix (like _balance) for internal/private properties.


๐Ÿงช Practice Challenge

Create a rectangle object with:

  • width and height properties
  • A getter area that returns width * height
  • A setter dimensions that sets both width and height via a string like "10x5"

Would you like this as:

  • ๐Ÿ’ป Interactive JS Fiddle/CodePen link?
  • ๐Ÿ“„ Downloadable PDF or notes?
  • ๐Ÿ“š Flashcards for revision?

Let me know and I can generate it for you!