Object Get And Set in JavaScript
Object Getters and Setters in JavaScript
What Are Getters and Setters?
Getters: Special methods to access (get) the value of an object property.
Setters: Special methods to modify (set) the value of an object property.
They allow control over how properties are accessed or changed.
Syntax
Using Object Literal
const person = { firstName: "John", lastName: "Doe", // Getter get fullName() { return this.firstName + " " + this.lastName; }, // Setter set fullName(name) { const parts = name.split(" "); this.firstName = parts[0]; this.lastName = parts[1]; }};console.log(person.fullName); // John Doeperson.fullName = "Jane Smith";console.log(person.firstName); // Janeconsole.log(person.lastName); // SmithUsing Object.defineProperty
const person = { firstName: "John", lastName: "Doe"};Object.defineProperty(person, 'fullName', { get: function() { return this.firstName + " " + this.lastName; }, set: function(name) { const parts = name.split(" "); this.firstName = parts[0]; this.lastName = parts[1]; }});console.log(person.fullName); // John Doeperson.fullName = "Jane Smith";console.log(person.firstName); // Janeconsole.log(person.lastName); // SmithWhy Use Getters and Setters?
Encapsulation: Hide internal representation.
Validation: Validate data before setting.
Computed properties: Dynamically calculate property values.
Summary
| Feature | Purpose | Example Usage |
|---|---|---|
| Getter | Access property value via method | obj.prop calls getter |
| Setter | Modify property value with control | obj.prop = value calls setter |
Want a demo with validation or computed values?