WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 56 of 100

Can you explain the purpose and usage of JavaScript Proxy objects?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

JavaScript Proxy objects were introduced in ECMAScript 6 and are a powerful way to intercept and control the behavior of JavaScript objects. A Proxy object acts as an intermediary between a client object and the client code that accesses it, allowing developers to intercept and customize operations on the object.

Proxy objects work by defining a set of traps, which are special methods that are invoked whenever a corresponding operation is performed on the target object. These traps can be used to intercept and handle a wide range of operations, including property access, assignment, deletion, enumeration, and function invocation.

Here’s an example that demonstrates the basic usage of a Proxy object:

    const target = {
        name: 'John',
        age: 30
    };
    
    const handler = {
        get(target, property) {
            console.log(`Getting ${property}`);
            return target[property];
        },
        
        set(target, property, value) {
            console.log(`Setting ${property} to ${value}`);
            target[property] = value;
        }
    };
    
    const proxy = new Proxy(target, handler);
    
    proxy.name; // Output: Getting name, returns 'John'
    proxy.age = 35; // Output: Setting age to 35

In the example, we create a target object with two properties, name and age. We then define a handler object with two traps: get and set. The get trap intercepts property access and logs a message before returning the value of the property. The set trap intercepts property assignment and logs a message before setting the new value.

Finally, we create a Proxy object that wraps the target object and uses the handler to intercept all operations on the object. When we access the name property on the proxy, the get trap intercepts the operation and logs a message before returning the value of the property. Similarly, when we assign a new value to the age property on the proxy, the set trap intercepts the operation and logs a message before setting the new value.

Proxy objects are often used in advanced scenarios such as data validation, memoization, and caching. They provide a flexible and powerful way to customize and control the behavior of JavaScript objects, making them an important tool in the JavaScript developer’s toolkit.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics