What is the output of the following code? const handler = { set(target, prop, value) { if (typeof value !== ‘number’) throw new TypeError(‘Numbers only’); return Reflect.set(target, prop, value); } }; const numObj = new Proxy({}, handler); numObj.a = 5; numObj.b = ‘hi’; console.log(numObj.a);

JavaScript Professional Hard

JavaScript Professional — Hard

What is the output of the following code? const handler = { set(target, prop, value) { if (typeof value !== ‘number’) throw new TypeError(‘Numbers only’); return Reflect.set(target, prop, value); } }; const numObj = new Proxy({}, handler); numObj.a = 5; numObj.b = ‘hi’; console.log(numObj.a);

Key points

  • The handler function only allows number assignments
  • The code throws a TypeError when trying to assign a string
  • The console.log statement is never reached
  • Proxy handler enforces specific rules for property assignments

Ready to go further?

Related questions