5.3. Empty an object in place
Topics
This question is in
5. Objects and property controlsettings = {} gives you a new empty object, but every other part of the program still holds the old one, full of data. Sometimes the object itself must be emptied: a cache that several modules share, a form state object passed around by reference, a registry that a library keeps. Emptying it in place means deleting its properties one by one, and that raises real questions: which properties does a key list leave out, and what happens when one cannot be deleted?
Write clearObject(object) in clear-object.js. It removes every own property that can be removed and returns the same object.
Signature
function clearObject(object) // returns the same objectobject: the object to empty, changed in place.- Returns
objectitself, not a copy.
Requirements
- Every own property is removed: string keys and symbol keys, enumerable and non-enumerable, data properties and getters/setters.
- The same object is returned, so every reference to it sees it empty.
- Getters and setters are removed without being called.
- The prototype is kept, so inherited methods still work, and the prototype's own properties are not touched.
- A property that cannot be deleted (non-configurable, or on a frozen or sealed object) stays where it is, and no error is thrown.
- It works on an object without a prototype (
Object.create(null)), and on an object with its ownhasOwnPropertyproperty. - It throws a
TypeErrorwhenobjectisnull,undefinedor a primitive.
Examples
const cache = { a: 1, b: 2 };
const sameCache = cache;
clearObject(cache); // returns cache
sameCache; // {}: the same object, now emptyconst tag = Symbol("tag");
const object = { visible: 1, [tag]: 2 };
Object.defineProperty(object, "hidden", { value: 3, enumerable: false, configurable: true });
clearObject(object); // all three are goneconst record = {};
Object.defineProperty(record, "id", { value: 7, enumerable: true, configurable: false });
record.note = "temp";
clearObject(record); // { id: 7 }: id cannot be deleted; no error
clearObject(Object.freeze({ a: 1 })); // { a: 1 }, no errorEnvironment
- Plain JavaScript in a browser page; the tests call the global
clearObjectfromclear-object.js. - Every built-in is allowed. Arrays (whose
lengthcannot be deleted) and functions are out of scope.
Hints
Object.keysleaves out two kinds of keys. Which function lists every own key?- What does
deletedo with a non-configurable property in strict mode, and is there a way to delete that reports failure instead?
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