A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-getters-and-setters/ below:

JavaScript Getters and Setters - GeeksforGeeks

JavaScript Getters and Setters

Last Updated : 05 Aug, 2025

In JavaScript, getter and setter are the special methods introduced in ECMAScript 5 (ES5 2009) that allow us to retrieve and modify the values directly without directly changing the object property. The getter uses the get keyword and the setter uses the set keyword to modify and retrieve the values.

JavaScript Getter (The get Keyword)

In JavaScript, the getter is the method that is used to get the value of the property. We can use the get keyword to get the value of the property.

JavaScript
class P {
    constructor(name) {
        this._name = name;
    }

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

const res = new P('Anjali');
console.log(res.name);

In this example

Getter vs Regular Function

In JavaScript, the getter and the regular functions both are used for the accessing the object properties but in the different ways. Getters allow properties to be accessed like regular object attributes while still executing logic in the background. On the other hand, regular functions require explicit method calls and do not provide direct property-like access.

Feature

Getter (get)

Regular Function

Syntax

Accessed like a property (obj.prop)

Called explicitly (obj.method())

Readability

Improves readability & simplicity

equires () which makes it look like a method call

Encapsulation

Can restrict direct access to properties

Properties can be easily accessed

JavaScript Setter (The set Keyword)

In JavaScript, the setter is the method that is used for setting the value of the property with the help of the set keyword.

JavaScript
class P {
    constructor(name) {
        this._name = name;
    }

    set name(newName) {
        this._name = newName;
    }
}

const res = new P('Anjali');
res.name = 'Ayushi'; // Using the setter to change the name
console.log(res._name); // Output: Ayushi

In this example

Implementing Getters and Setters in JavaScript Using Getters and Setters in Objects

In objects, we can use the get and set keywords for defining the getter and setter in objects.

JavaScript
const p= {
    n1: "Anurag",
    n2: "Das",
    get Name() {
        return `${this.n1} ${this.n2}`;
    },
    set Name(name) {
        [this.n1, this.n2] = name.split(" ");
    }
};

console.log(p.Name);
p.Name = "Anuj Jain";
console.log(p.Name); 

Output
Anurag Das
Anuj Jain
Getters and Setters with Classes

Getters and setters are commonly used in ES6 classes to control access to private properties.

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

    get a() {
        return this.width * this.height;
    }

    set a(value) {
        console.log("Area cannot be set directly.");
    }
}

const rect = new R(10, 5);
console.log(rect.a);
rect.a = 60; 

Output
50
Area cannot be set directly.

The getter computes the area dynamically, and the setter prevents modification, enforcing encapsulation.

Using Getters and Setters with Private Fields

With ES2020, JavaScript introduced private fields (prefix _ is just a convention; # makes it truly private).

JavaScript
class B {
    #balance; // Private property

    constructor(balance) {
        this.#balance = balance;
    }

    get balance() {
        return this.#balance;
    }

    set balance(amount) {
        if (amount < 0) {
            console.log("Balance cannot be negative!");
        } else {
            this.#balance = amount;
        }
    }
}

const acc = new B(1000);
console.log(acc.balance);
acc.balance = -500;  // "Balance cannot be negative!"

Output
1000
Balance cannot be negative!

The #balance field is private, ensuring external code cannot modify it directly.

Using Object.defineProperty() for Accessors

The Object.defineProperty() method can define getters and setters dynamically.

JavaScript
const u = { name: "Anjali" };

Object.defineProperty(u, "greeting", {
    get: function () {
        return `Hello, ${this.name}!`;
    },
    set: function (newName) {
        this.name = newName;
    }
});

console.log(u.greeting);
u.greeting = "Ayushi";
console.log(u.greeting);

Output
Hello, Anjali!
Hello, Ayushi!

This approach allows defining dynamic properties with controlled access.

Use Cases of Getters and Setters When to Use Getters and Setters? When you need to validate input before assigning a value.
set age(value) {
    if (value < 0) throw new Error("Age cannot be negative!");
    this._age = value;
}
When properties depend on other properties (computed properties).
get fullName() {  
    return `${this.firstName} ${this.lastName}`;
}
When working with private fields in classes.
class Person {
    #secret = "Hidden Data";
    get secret() {
        return "Access Denied";
    }
}
When debugging changes in properties.
set value(newValue) {
    console.log(`Value changed to: ${newValue}`);
    this._value = newValue;
}
Getters and Setters vs. Direct Property Access

Feature

Getters & Setters

Direct Property Access

Definition

Special methods used to control the access and modification of object properties.

Directly assigning and retrieving values from an object's properties without any additional control.

Use Cases

Used when validation, computed properties, encapsulation, or logging is required.

Used for simple data storage where additional logic is not needed.

Performance

Slightly slower due to method calls.

Faster since it directly accesses properties.

Encapsulation

Provides encapsulation by restricting direct access to internal data.

No encapsulation; data can be freely modified.

Simplicity

More complex as it requires defining getter/setter methods.

Easier to use since properties can be accessed directly.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4