What they are: Properties that look normal but run functions when you access or change them.
Basic Syntax - Two Ways to Create:
Method 1: Object Literal
javascript
let user = {
name: "John",
surname: "Smith",
get fullName() {
return `${this.name} ${this.surname}`;
},
set fullName(value) {
[this.name, this.surname] = value.split(" ");
}
};
// Looks like normal property access
console.log(user.fullName); // "John Smith" (runs getter)
user.fullName = "Alice Cooper"; // Runs setter
console.log(user.name); // "Alice"Method 2: defineProperty
javascript
let user = { name: "John", surname: "Smith" };
Object.defineProperty(user, 'fullName', {
get() {
return `${this.name} ${this.surname}`;
},
set(value) {
[this.name, this.surname] = value.split(" ");
}
});How They Work - The Magic:
From outside, it looks like a normal property:
javascript
// These look the same:
user.fullName; // Getter function runs
user.name; // Regular property access
// These look the same:
user.fullName = "Bob Dylan"; // Setter function runs
user.name = "Bob"; // Regular property assignmentBut behind the scenes:
javascript
// When you do: user.fullName
// JavaScript actually calls: user.get fullName()
// When you do: user.fullName = "value"
// JavaScript actually calls: user.set fullName("value")Real-World Examples:
Example 1: Computed Properties
javascript
let rectangle = {
width: 10,
height: 5,
get area() {
return this.width * this.height;
}
// No setter - area is read-only
};
console.log(rectangle.area); // 50
rectangle.width = 20;
console.log(rectangle.area); // 100 (automatically updated!)Example 2: Validation
javascript
let user = {
_name: "",
get name() {
return this._name;
},
set name(value) {
if (value.length < 2) {
console.log("Name too short!");
return;
}
this._name = value;
}
};
user.name = "John"; // Works
user.name = "J"; // "Name too short!"
console.log(user.name); // "John" (unchanged)Example 3: Data Transformation
javascript
let temperature = {
_celsius: 0,
get celsius() {
return this._celsius;
},
set celsius(value) {
this._celsius = value;
},
get fahrenheit() {
return this._celsius * 9/5 + 32;
},
set fahrenheit(value) {
this._celsius = (value - 32) * 5/9;
}
};
temperature.celsius = 25;
console.log(temperature.fahrenheit); // 77
temperature.fahrenheit = 86;
console.log(temperature.celsius); // 30