What is a Proxy in JavaScript and what are its use cases?
Suggested answer
A Proxy wraps an object and intercepts fundamental operations (get, set, delete, etc.) via trap functions. Syntax: const proxy = new Proxy(target, handler);. Common traps: get(target, prop): Intercept property access. set(target, prop, value): Intercept property assignment. has(target, prop): Intercept the in operator. deleteProperty(target, prop): Intercept delete. Use cases:
1. Validation: Throw errors when invalid values are set on an object.
2. Logging/debugging: Log all property accesses.
3. Default values: Return a default when a property doesn't exist (avoid undefined).
4. Reactive systems: Vue.js 3's reactivity system is built on Proxy.
5. Immutable objects: Prevent writes in the set trap. LWC's internal reactivity for @track uses Proxy-like mechanisms under the hood.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.