Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
5.5. A property that can be set only once
Medium
Topics
This question is in
5. Objects and property controlSome values are decided once and must never change afterwards: an order's id once the server has assigned it, the user a session belongs to, a configuration value read at start-up. A later write to them is always a bug, and the earlier it is caught, the easier it is to find. A property can enforce that itself: the first assignment is stored, and any later one throws.
Write defineWriteOnce(object, key) in write-once.js. It adds a property key to object that can be assigned exactly once.
Signature
function defineWriteOnce(object, key) // returns objectobject: the object to add the property to. It does not already havekey.key: the property name.- Returns
objectitself.
Requirements
- The property exists right away (
key in objectistrue) and reads asundefineduntil it is set. Reading never counts as setting. - The first assignment stores its value.
- Every later assignment throws a
TypeErrorwhose message names the property, and the first value stays. Assigning the same value again also throws. - The first assignment counts whatever its value is: after
object.id = undefined(ornull,0,"",false,NaN), the next assignment throws. - The rule holds in strict-mode code and sloppy code alike, and for
Object.assign. - The property is enumerable (
Object.keys,JSON.stringify), and it cannot be deleted or redefined withObject.defineProperty. - Each property has its own state: two keys on one object, or the same key on two objects, are independent.
- No other property is added to the object.
Examples
const order = defineWriteOnce({ total: 250 }, "id");
order.id; // undefined
order.id = "A-17";
order.id; // "A-17"
order.id = "B-02"; // TypeError: "id" can be set only once
order.id; // "A-17"const session = defineWriteOnce({}, "user");
session.user = undefined; // counts as the one assignment
session.user = "asha"; // TypeErrordelete order.id; // false: still "A-17"
Object.defineProperty(order, "id", { value: 1 }); // TypeError
JSON.stringify(order); // '{"total":250,"id":"A-17"}'Environment
- Plain JavaScript in a browser page; the tests call the global
defineWriteOncefromwrite-once.js. - Every built-in is allowed.
Object.freezeon the whole object is not a solution: other properties must stay writable.
Hints
- A non-writable data property ignores writes silently in sloppy code. What kind of property can throw on every write?
- How do you remember "it was set" when the value that was set is
undefined?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…