Getters, Setters & Property Descriptors
Published by Brayan K
Getters and setters are special functions that run when you read or assign a property, letting you compute values and validate input behind plain property syntax — while property descriptors control whether each property is writable, enumerable, and configurable.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Reading a property can run a function
Property syntax does not tell you whether a stored value is being retrieved or a function is running. A getter runs on a read; a setter runs on an assignment. This can make a small API pleasant to use, but it also means logging, spreading or serializing an object may trigger behavior that a reader did not expect.
// Store inputs as fields and compute the derived value on access.
const item = {
quantity: 2,
unitPrice: 5,
get total() { return this.quantity * this.unitPrice; }
};
console.log(item.total);
item.quantity = 3;
console.log(item.total);
const descriptor = Object.getOwnPropertyDescriptor(item, "total");
console.log(typeof descriptor.get, descriptor.set);
console.log(Object.hasOwn(descriptor, "value"));
// ✅ Expected output:
// 10
// 15
// function undefined
// falseThe getter is not called with parentheses when accessing the property. Its return value becomes the read result. This example is cheap and predictable. A getter that performs network work, mutates unrelated state or sometimes throws should not be mistaken for a harmless field access.
let stored = "";
const item = {
get label() { return stored; },
set label(value) { stored = value.trim(); return "ignored"; }
};
const expression = (item.label = " Mina ");
console.log(JSON.stringify(expression), JSON.stringify(item.label));
// ✅ Expected output:
// " Mina " "Mina"The setter’s return value is discarded. Validate before updating backing state, and avoid writing the same accessor from inside its setter: assigning this.label in this label setter would recurse. Here the closure variable has a different name and does not trigger the setter.
A descriptor describes one kind of property
const item = {};
Object.defineProperty(item, "score", { value: 7 });
const descriptor = Object.getOwnPropertyDescriptor(item, "score");
console.log(JSON.stringify(descriptor));
console.log(Object.keys(item).length);
console.log(Reflect.set(item, "score", 8), Reflect.deleteProperty(item, "score"));
console.log(item.score);
// ✅ Expected output:
// {"value":7,"writable":false,"enumerable":false,"configurable":false}
// 0
// false false
// 7For a new data property defined this way, omitted writable, enumerable and configurable flags are false. Ordinary object-literal fields default to true for those flags. When updating an existing property, omitted descriptor fields keep their existing settings; omission is not an instruction to reset everything.
const item = { score: 1 };
Object.defineProperty(item, "score", { value: 2 });
console.log(JSON.stringify(Object.getOwnPropertyDescriptor(item, "score")));
// ✅ Expected output:
// {"value":2,"writable":true,"enumerable":true,"configurable":true}Object.defineProperty({}, "score", {
value: 2,
get() { return 3; }
});
// ✅ Expected error:
// TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object>A data descriptor uses value and writable. An accessor descriptor uses get and set. Both can use enumerable and configurable. A missing getter makes reads return undefined; a missing setter refuses assignment. Configurable controls deletion and most later descriptor changes; it is not the same flag as writable.
"use strict";
const item = { get score() { return 7; } };
item.score = 8;
// ✅ Expected error:
// TypeError: Cannot set property score of #<Object> which has only a getterconst item = { get score() { return 7; } };
console.log(Reflect.set(item, "score", 8));
console.log(item.score);
// ✅ Expected output:
// false
// 7Reflect.set returning false is distinct from an exception thrown inside a setter. Reflect does not swallow exceptions from user code. Use explicit strict mode when demonstrating direct-assignment errors so the result does not depend on whether the caller is a script or module.
The receiver determines which object a getter observes
const base = {
name: "base",
get greeting() { return "Hello " + this.name; }
};
const child = Object.create(base);
child.name = "child";
console.log(child.greeting);
console.log(Reflect.get(base, "greeting", { name: "receiver" }));
console.log(Object.hasOwn(child, "greeting"));
// ✅ Expected output:
// Hello child
// Hello receiver
// falseThe getter definition is on base, but a read through child uses child as this. Reflect.get can supply a receiver explicitly. Arrow functions do not acquire this from the property access, so use a method-style getter when that receiver matters. The this Keyword owns general receiver binding.
const base = {
set label(value) { this.saved = value.trim(); },
get label() { return this.saved; }
};
const child = Object.create(base);
child.label = " note ";
console.log(child.label, Object.hasOwn(child, "label"), Object.hasOwn(child, "saved"));
console.log(Object.hasOwn(base, "saved"));
// ✅ Expected output:
// note false true
// falseThis behavior is useful for a deliberate API, but it is not a guarantee that every assignment creates an own property with the assigned name. Prototype Chain & Advanced OOP Patterns owns prototype lookup. Proxy & Reflect (Metaprogramming) applies receivers to intercepted operations.
Copying a value and copying its descriptor do different work
let current = 2;
let reads = 0;
const source = { get score() { reads++; return current; } };
const values = { ...source };
const descriptors = Object.create(Object.getPrototypeOf(source), Object.getOwnPropertyDescriptors(source));
console.log(reads);
current = 5;
console.log(values.score, descriptors.score, reads);
console.log(Object.getOwnPropertyDescriptor(descriptors, "score").get === Object.getOwnPropertyDescriptor(source, "score").get);
// ✅ Expected output:
// 1
// 2 5 2
// trueThe descriptor copy reuses the getter function; it does not clone its closed-over state. It also preserves descriptor flags. That is useful for this ordinary object, but it does not recreate internal slots of built-in objects or magically deep-copy an arbitrary instance. Deep Copy vs Shallow Copy & Data Structures owns those broader copying limits.
let current = 1;
const item = Object.freeze({
get value() { return current; },
set value(next) { current = next; }
});
item.value = 9;
console.log(Object.isFrozen(item), item.value);
console.log(Object.getOwnPropertyDescriptor(item, "value").configurable);
// ✅ Expected output:
// true 9
// falseThe accessor remains installed and non-configurable. Its setter still runs. Object.freeze protects own property structure and data-property writes; it does not inspect or freeze closure variables. Use this deliberately, and document whether your API is a frozen handle to mutable state or an immutable value.
Guided exercise: define a computed, enumerable field
Fill each literal hint. A getter reads the latest quantity, and enumeration lists it because its descriptor explicitly permits that.
const item = { quantity: 3 };
Object.defineProperty(item, "double", {
___() { return this.quantity * 2; }, // 👉 replace ___ with get
enumerable: ___ // 👉 replace ___ with true
});
console.log(item.double);
item.quantity = ___; // 👉 replace ___ with 4
console.log(item.double, Object.keys(item).join(","));
// ✅ Expected output:
// 6
// 8 quantity,doubleBrief: a meter with a frozen handle and changing state
Implement createMeter(initial = 0). Accept integers from 0 through 1000, without coercion; normalize negative zero. Expose enumerable value and revision accessors. revision starts at zero and increases only when a valid assignment actually changes value. Reassigning the same normalized number changes nothing.
Validate before changing state. Reject invalid values with RangeError("value must be an integer from 0 to 1000"). If a genuine change would increment revision past Number.MAX_SAFE_INTEGER, throw RangeError("revision limit") without changing value. The non-enumerable snapshot method returns a fresh frozen ordinary record containing value and revision. Freeze the public handle, and explain why its value setter still works.
function createMeter(initial = 0) {
const valid = value => Number.isInteger(value) && value >= 0 && value <= 1000;
if (!valid(initial)) throw new RangeError("value must be an integer from 0 to 1000");
let current = initial === 0 ? 0 : initial;
let revision = 0;
const meter = {};
Object.defineProperties(meter, {
value: {
enumerable: true,
get() { return current; },
set(next) {
if (!valid(next)) throw new RangeError("value must be an integer from 0 to 1000");
const normalized = next === 0 ? 0 : next;
if (normalized === current) return;
if (revision === Number.MAX_SAFE_INTEGER) throw new RangeError("revision limit");
current = normalized;
revision++;
}
},
revision: { enumerable: true, get() { return revision; } },
snapshot: {
value() { return Object.freeze({ value: current, revision }); },
enumerable: false
}
});
return Object.freeze(meter);
}
const meter = createMeter(-0);
const first = meter.snapshot();
meter.value = 5;
meter.value = 5;
console.log(meter.value, meter.revision, Object.isFrozen(meter));
console.log(JSON.stringify(first), JSON.stringify(meter.snapshot()));
console.log(first === meter.snapshot(), Object.is(meter.value, -0));
try { meter.value = 1.5; } catch (error) { console.log(error.name, error.message); }
console.log(meter.value, meter.revision, Object.keys(meter).join(","));
// ✅ Expected output:
// 5 1 true
// {"value":0,"revision":0} {"value":5,"revision":1}
// false false
// RangeError value must be an integer from 0 to 1000
// 5 1 value,revisionThe overflow guard is an explicit limit; executing trillions of changes is not a practical test. Ordinary value changes, invalid writes, unchanged writes, snapshots and descriptors can be checked directly. This object does not implement storage, observers or cross-process synchronization.
Practice quiz
What does this complete program print? let n = 1; const x = { get value() { return n; } }; console.log(x.value); n = 2; console.log(x.value);
- 1 2
- 1 1
- 2 2
- undefined undefined
Answer: 1 2. A getter runs again on each read.
What does this complete program print? const x = {}; Object.defineProperty(x, "a", { value: 1 }); console.log(Object.keys(x).length, Reflect.set(x, "a", 2));
- 1 true
- 0 false
- 0 true
- 1 false
Answer: 0 false. The newly defined property is non-enumerable and non-writable by default.
What does this complete program print? let n = 0; const x = { set value(v) { n = v * 2; return 99; } }; console.log(x.value = 3, n);
- 99 6
- 6 6
- 3 6
- undefined 6
Answer: 3 6. The assignment expression yields the original right-hand value, not the setter result.
What does this complete program print? const x = { a: 1 }; Object.defineProperty(x, "a", { value: 2 }); console.log(Object.getOwnPropertyDescriptor(x, "a").writable);
- false
- undefined
- TypeError
- true
Answer: true. Omitted fields retain the existing descriptor settings during an update.
What does this complete program print? const base = { get name() { return this.label; } }; console.log(Reflect.get(base, "name", { label: "reader" }));
- reader
- undefined
- base
- TypeError
Answer: reader. Reflect.get supplies the explicit receiver to the getter.
What does this complete program print? let n = 1; const x = Object.freeze({ set value(v) { n = v; } }); x.value = 4; console.log(n);
- 1
- 4
- undefined
- TypeError
Answer: 4. The setter can change closure state despite frozen property definitions.
What does this complete program print? let n = 2; const x = { get value() { return n; } }; const y = { ...x }; n = 7; console.log(y.value);
- 7
- undefined
- 2
- TypeError
Answer: 2. Spread reads and stores the current value; it does not preserve this getter.
What does this complete program print? const x = { get value() { return 3; } }; console.log(Reflect.set(x, "value", 4), x.value);
- true 4
- true 3
- false 4
- false 3
Answer: false 3. A getter-only property refuses the write and retains its read behavior.
Continue this course
- Previous: Symbols & Well-Known Symbols
- Next: Proxy & Reflect (Metaprogramming) — Intercept object operations with traps — the basis of modern reactivity
- Quick reference: JavaScript cheat sheet