🟡 MediumModern JS📖 Theory Question

What is Reflect and how does it relate to Proxy?

💡

Hint

Reflect mirrors Proxy trap methods — use Reflect inside traps for correct default behavior

Full Answer

Reflect is a built-in object with static methods mirroring Proxy traps — same names, same signatures.

// Reflect mirrors operations but with better API design:
Reflect.get(target, prop, receiver);    // target[prop]
Reflect.set(target, prop, value, recv); // target[prop] = value
Reflect.has(target, prop);              // prop in target
Reflect.deleteProperty(target, prop);  // delete target[prop]
Reflect.ownKeys(target);               // all own keys (strings + symbols)
Reflect.apply(fn, thisArg, args);      // fn.apply(thisArg, args)
Reflect.construct(Cls, args);          // new Cls(...args)

// Why Reflect inside Proxy traps?
const proxy = new Proxy(obj, {
  get(target, prop, receiver) {
    log(prop);
    // Use Reflect.get (not target[prop]) to:
    // 1. Correctly pass receiver (preserves 'this' for getters)
    // 2. Return consistent boolean values
    return Reflect.get(target, prop, receiver); // ✅
    // return target[prop]; // ❌ breaks for inherited getters
  }
});

// Reflect.set returns true/false instead of throwing
const success = Reflect.set(obj, 'x', 5);
if (!success) console.log('Could not set');
💡 Rule: always use Reflect inside Proxy traps. It handles prototype chain, getters/setters, and non-writable properties correctly. Never do target[prop] directly in get trap.

More Modern JS Questions

🟡 MediumWhat are generators and when would you use them?🟢 EasyWhat is optional chaining (?.) and nullish coalescing (??)?🟢 EasyWhat are tagged template literals and what are they used for?🟢 EasyExplain destructuring for objects and arrays — including defaults, renaming, rest, and nesting.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint