A setter that validates
The two bad assignments ran the setter, which refused them. Real code would usually throw an error instead of logging.
A getter is a property that runs a function when you read it, and a setter runs a function when you assign to it; behind every property sits a descriptor that decides whether it can be changed, listed or deleted, which you read with Object.getOwnPropertyDescriptor and set with Object.defineProperty.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Make person with first and last and an accessor fullName: reading gives "first last", assigning "Meera Nair" splits it into first and last. Log the result of both.
Use Object.defineProperty to add a read-only but listed createdAt to const note = { text: "Hi" }. Show that it appears in Object.keys but can't be changed.
Make cart with an items array of { price, qty } and a getter total. Log cart.total, push an item, log it again.
Explain it without notes
What is the difference between a data property and an accessor property?
What are writable, enumerable and configurable?
Why does Object.defineProperty(obj, "x", { value: 1 }) behave differently from obj.x = 1?
What causes Maximum call stack size exceeded in a setter, and how do you avoid it?
Preview
Console
Nothing logged yet.Expected console output
Rejected: -20
Rejected: lots
500