Advanced Objects: Descriptors, Proxy and Iterators
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Inspect and control property behavior with descriptors.
- Use Proxy and Reflect to intercept object operations.
- Build custom iterables and generators, and memoize expensive work.
Overview
#Property descriptors
Every property has a descriptor that records its value, whether it is writable, enumerable and configurable. Object.defineProperty lets you set these flags and define getters and setters. A getter runs when the property is read; a setter runs when it is written. Non-enumerable properties are skipped by spread, Object.keys and for..in.
const point = {};
Object.defineProperty(point, 'x', {
get() { return this._x; },
set(value) { this._x = value * 2; },
enumerable: true,
});
point.x = 3;
console.log(point.x); // 6
Proxy and Reflect
A Proxy wraps a target and intercepts operations through traps such as get, set, has and deleteProperty. Reflect provides the default behavior for each trap, so a proxy can log or validate and then delegate. Proxies power reactive frameworks, validation layers and virtual objects.
Iterators and generators
An iterable exposes Symbol.iterator returning an iterator with a next method. A generator function, written with function*, produces values lazily with yield and implements the iterator protocol automatically. Generators are useful for lazy sequences and for pausing work.
Memoization and performance
Memoization caches a function's result by its arguments. A Map keyed by a stable representation is the usual implementation. Cache only pure functions, and bound the cache if the argument space is large. Measuring before optimizing keeps the work honest.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this print?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptconst point = {}; Object.defineProperty(point, 'x', { get() { return this._x; }, set(value) { this._x = value * 2; }, }); point.x = 3; console.log(point.x);Exercise 2Explain
Explain what this Proxy logs and why Reflect is used inside the trap.
starter.javascriptconst target = { a: 1 }; const proxy = new Proxy(target, { get(obj, key) { console.log('read ' + String(key)); return Reflect.get(obj, key); }, }); console.log(proxy.a);Reveal the reference answer
reference.javascriptReading proxy.a triggers the get trap, which logs 'read a' and then returns Reflect.get(target, 'a'). Reflect.get performs the default read, so the proxy forwards the operation to the target without reimplementing property lookup. The final log is the value 1.Authored expected output: read a 1
The trap intercepts the operation, and Reflect supplies the default behavior so the proxy stays correct for inherited and accessor properties.
Exercise 3Implement
Implement `memoize(fn)` using a Map cache. Running `const slow = memoize((n) => { console.log('compute'); return n * n; }); console.log(slow(4), slow(4));` should print `compute` once, then `16 16`.
starter.javascriptfunction memoize(fn) { // your code here }Reveal the reference answer
reference.javascriptfunction memoize(fn) { const cache = new Map(); return function (arg) { if (cache.has(arg)) return cache.get(arg); const result = fn.call(this, arg); cache.set(arg, result); return result; }; }Authored expected output: compute 16 16
The cache lives in the closure. The first call runs fn and stores the result; the second call finds the key and returns the cached value, so 'compute' prints only once.
Exercise 4Debug
This code defines a hidden internal field but the field shows up in Object.keys and in JSON output. Make it non-enumerable.
starter.javascriptconst record = { id: 1 }; record._internal = 'secret'; console.log(Object.keys(record));Reveal the reference answer
reference.javascriptconst record = { id: 1 }; Object.defineProperty(record, '_internal', { value: 'secret', enumerable: false, writable: true, configurable: true, }); console.log(Object.keys(record));Authored expected output: [ 'id' ]
Plain assignment creates an enumerable property. Object.defineProperty with enumerable false hides the field from Object.keys, spread and JSON serialization while keeping it readable directly.
Exercise 5Test
Write a test that proves a generator yields values lazily and can be consumed with for..of.
starter.javascriptfunction* range(start, end) { for (let i = start; i < end; i++) yield i; }Reveal the reference answer
reference.javascriptconst seen = []; for (const value of range(1, 4)) seen.push(value); if (seen.join(',') !== '1,2,3') throw new Error('wrong values'); const iterator = range(0, 2); if (iterator.next().value !== 0) throw new Error('first'); if (iterator.next().done) throw new Error('not done early'); console.log('generator verified');Authored expected output: generator verified
The generator implements the iterator protocol, so for..of consumes it. Calling next manually shows values are produced one at a time rather than all at once.
Exercise 6Interview
Describe a real use of Proxy and one risk it introduces.
Reveal the reference answer
reference.javascriptA Vue-style reactive system wraps state in a Proxy whose get trap records which properties a render function reads and whose set trap schedules an update when a tracked property changes. The risk is that proxies add a layer to every property access, which costs performance on hot paths, and that a trap which forgets to use Reflect can break invariants such as non-configurable properties. I use proxies for cross-cutting concerns and measure before adopting them widely.The answer should name a concrete framework-level use and a concrete cost or invariant risk, showing that the tool is understood rather than admired.
Common misconceptions
#- Object.keys lists every property on an object, including non-enumerable ones.
- A Proxy copies the target rather than intercepting access to it.
- Memoization is safe for any function, including ones with side effects.
Follow-up practice
#- javascript-foundations-symbols-and-well-known-symbols
- javascript-foundations-property-accessors-and-descriptors
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.