Spread with Getters and Setters
You'll learn how the spread operator interacts with getter methods on objects—and why it copies values, not behaviors.
The Core Idea
When you use the spread operator (...) on an object that has getters (accessor properties), JavaScript doesn't copy the getter function itself. Instead, it invokes the getter and copies the returned value as a regular data property.
Think of it like taking a photo of a vending machine. You don't get a working vending machine—you get a picture showing what was inside at that moment.
How It Works
const original = {
_value: 10,
get double() {
return this._value * 2;
}
};
console.log(original.double); // 20 (getter invoked)
const copy = { ...original };
console.log(copy.double); // 20 (just a regular property now)
original._value = 50;
console.log(original.double); // 100 (getter recalculates)
console.log(copy.double); // 20 (static value, no getter!)
The copy object has a plain property double: 20, not a dynamic getter. Changing _value in original doesn't affect copy because the behavior wasn't copied—only the snapshot value.
The Same Applies to Setters
const obj = {
_temp: 0,
set temperature(val) {
this._temp = val;
console.log("Temperature set!");
}
};
const spread = { ...obj };
// spread has _temp: 0 and temperature: undefined
// No setter function exists on spread
Setters aren't invoked or copied during spread. You only get the underlying data properties.
Key Takeaway: Spread copies the current values from getters and setters, not the accessor functions themselves. The result is a plain object with static data properties.