How to add getter to an existing JavaScript Object

In this article, we will learn how to add getter to an existing JavaScript Object.

In JavaScript, we can add a getter to an object using the get syntax.

The get syntax, let us to bind a Javasrcipt property to a function that can be called as any object property.

Syntax:

{get prop() { /* ... */ } }

Now let see an example

const student = {
    firstName: 'John',
    lastName: 'Adams',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    }
};

console.log(student.firstName)
console.log(student.fullName) //calling the getter method

Output:

John
John Adams

In the above code, we have created the getter method fullName() using the get keyword. And to get the value, we can access it as any javascript property using student.fullName .

From the above example, we know how to create a getter method and access the value of the property.

Now, let’s see how we can add a getter method to an existing JavaScript object.

Add getter method to existing object in Javascript

To add an getter to an existing object we have to use the Object.defineproperty method.

The Object.defineProperty()is a static method that defines a new property directly to an object, it can also modify an existing property on an object.

Syntax:

Object.defineProperty(obj, prop, descriptor)

obj the object on which we add the getter method.

prop – the name or property to be defined

descriptor – the descriptor for the property.

Let’s take the above example and add the fullName after the student object is already created.

const student = {
    firstName: 'John',
    lastName: 'Adams',
};

Object.defineProperty(student, 'fullName', {
  get: function() { return this.firstName + ' ' + this.lastName }
});

console.log(student.fullName)

Output:

John Adams
Scroll to Top