JavaScript Fundamentals / Classes

Getter and Setters

Getter (get)

  • Used to read a property

  • Looks like a normal property but runs a function behind the scenes

Setter (set)

  • Used to update a property

  • Allows validation, logic, or formatting before assigning


✅ Basic Example

class Person {
  constructor(name) {
    this._name = name; // underscore means "internal property"
  }

  get name() {
    return this._name.toUpperCase();
  }

  set name(value) {
    this._name = value.trim();
  }
}

const p = new Person("Raman");
console.log(p.name); 
// Raman  (getter called)

p.name = "  Sharma  ";  // setter called
console.log(p.name); 
// Sharma (getter called)

🔍 What’s happening?

  • p.name → calls getter

  • p.name = " Saha " → calls setter

  • Internally stored in _name


✅ Why use Getters and Setters?

✔ Add validation

set age(value) {
  if (value < 0) throw new Error("Age cannot be negative");
  this._age = value;
}

✔ Compute values dynamically

get fullName() {
  return `${this.first} ${this.last}`;
}

✔ Control how data is accessed and modified

✔ Keep internal data protected


✅ Using Getters/Setters Without Underscore?

Technically possible — but dangerous:

set name(value) {
  this.name = value; // ❌ infinite recursion
}

It keeps calling itself forever.

Always store internally using a different name (like _name).


✅ Class Property Access Looks Like Normal Variable

p.name   // NOT a function call
p.name() // ❌ incorrect

Getters make methods feel like properties — cleaner API.


✅ Quick Summary

Feature

Purpose

get

Reads a value with logic behind it

set

Writes a value with validation or formatting

Looks like property

No parentheses needed

Use internal field

Avoid recursion (e.g., _name)