Solve - Cannot set Property which has only a Getter in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Solve - Cannot set Property which has only a Getter #

The "Cannot set property which has only a getter" error occurs when trying to set a new value to a property, for which only a getter is defined. To solve the error, define a setter for the specific property.

index.js
class Person { constructor(first, last) { this.first = first; this.last = last; } // 👇️ getter get name() { return `${this.first} ${this.last}`; } } const p1 = new Person('John', 'Smith'); // ✅ Use getter console.log(p1.name); // ⛔️ Cannot set property name of #<Person> which has only a getter p1.name = 'John Doe';

We created a class in which we defined a name getter.

The getter allows us to get the full name by accessing the name property on an instance of the class.

Any time we access the name property on an instance of the class, the getter method name() is ran.

We then attempt to set the value for the name property on the class, however we haven't defined a setter for the property.

To solve the "Cannot set property which has only a getter" error, you have to define a setter for the property you are trying to update. The set syntax allows us to specify a function to be ran when the specific property is set.

index.js
class Person { constructor(first, last) { this.first = first; this.last = last; } get name() { return `${this.first} ${this.last}`; } // 👇️ Define setter set name(name) { this.first = name.split(' ')[0]; this.last = name.split(' ')[1]; } } const p1 = new Person('John', 'Smith'); // ✅ Use setter p1.name = 'James Doe'; console.log(p1.name); // 👉️ "James Doe"

We defined a setter for the name property. This means that any time we try to set the property on an instance, the setter method will be ran.

We updated the values for the first and last class properties in the method.

Notice that the value to the right of the equal sign gets passed as a parameter to the setter function.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.