DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • An Introduction to Object Mutation in JavaScript
  • A Comprehensive Guide To Working With JSON in JavaScript
  • JavaScript's Secret Weapon: Unraveling the Mysteries of Proxies
  • Modern Web Development With ReactJS: Best Practices and Tips

Trending

  • Hallucination Has Real Consequences — Lessons From Building AI Systems
  • Bridging Gaps in SOC Maturity Using Detection Engineering and Automation
  • Stop Using Python for Your GenAI Apps, Use Go and Genkit Instead
  • AI Agents Expose a Design Gap in Microservices Resilience Architecture
  1. DZone
  2. Coding
  3. JavaScript
  4. Metaprogramming With Proxies and Reflect in JavaScript

Metaprogramming With Proxies and Reflect in JavaScript

Covers syntax, key traps, and advanced use cases like validation, security, logging, and reactive systems, ideal for developers looking to harness programming techniques.

By 
Maulik Suchak user avatar
Maulik Suchak
·
Jan. 10, 25 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
5.2K Views

Join the DZone community and get the full member experience.

Join For Free

Metaprogramming is a powerful programming paradigm that allows code to dynamically manipulate its behavior at runtime. JavaScript, with the introduction of Proxies and the Reflect API in ES6, has taken metaprogramming capabilities to a new level, enabling developers to intercept and redefine core object operations like property access, assignment, and function invocation.

This blog post dives deep into these advanced JavaScript features, explaining their syntax, use cases, and how they work together to empower dynamic programming.

What Are Proxies?

A Proxy in JavaScript is a wrapper that allows developers to intercept and customize fundamental operations performed on an object. These operations include getting and setting properties, function calls, property deletions, and more.

Proxy Syntax

JavaScript
 
const proxy = new Proxy(target, handler);


  • target: The object being proxied.
  • handler: An object containing methods, known as traps, that define custom behaviors for intercepted operations.

Example: Logging Property Access

JavaScript
 
const user = { name: 'Alice', age: 30 };

const proxy = new Proxy(user, {
  get(target, property) {
    console.log(`Accessing property: ${property}`);
    return target[property];
  }
});

console.log(proxy.name); // Logs: Accessing property: name → Output: Alice


Key Proxy Traps

Trap Name Operation Intercepted
get Accessing a property (obj.prop or obj['prop'])
set Assigning a value to a property (obj.prop = value)
deleteProperty Deleting a property (delete obj.prop)
has Checking property existence (prop in obj)
apply Function invocation (obj())
construct Creating new instances with new (new obj())


Advanced Use Cases With Proxies

1. Input Validation

JavaScript
 
const user = { age: 25 };

const proxy = new Proxy(user, {
  set(target, property, value) {
    if (property === 'age' && typeof value !== 'number') {
      throw new Error('Age must be a number!');
    }
    target[property] = value;
    return true;
  }
});

proxy.age = 30;  // Works fine
proxy.age = '30'; // Throws Error: Age must be a number!


In this example, the set trap ensures type validation before allowing assignments.

2. Reactive Systems (Similar to Vue.js Reactivity)

JavaScript
 
const data = { price: 5, quantity: 2 };
let total = 0;

const proxy = new Proxy(data, {
  set(target, property, value) {
    target[property] = value;
    total = target.price * target.quantity;
    console.log(`Total updated: ${total}`);
    return true;
  }
});

proxy.price = 10;   // Logs: Total updated: 20
proxy.quantity = 3; // Logs: Total updated: 30


This code dynamically recalculates values whenever dependent properties are updated, mimicking the behavior of modern reactive frameworks.

What Is Reflect?

The Reflect API complements Proxies by providing methods that perform default behaviors for object operations, making it easier to integrate them into Proxy traps.

Key Reflect Methods

Method Description
Reflect.get(target, prop) Retrieves the value of a property.
Reflect.set(target, prop, val) Sets a property value.
Reflect.has(target, prop) Checks property existence (prop in obj).
Reflect.deleteProperty(target, prop) Deletes a property.
Reflect.apply(func, thisArg, args) Calls a function with a specified this context.
Reflect.construct(target, args) Creates a new instance of a constructor.


Example: Using Reflect for Default Behavior

JavaScript
 
const user = { age: 25 };

const proxy = new Proxy(user, {
  set(target, property, value) {
    if (property === 'age' && typeof value !== 'number') {
      throw new Error('Age must be a number!');
    }
    return Reflect.set(target, property, value); // Default behavior
  }
});

proxy.age = 28;  // Sets successfully
console.log(user.age); // Output: 28


Using Reflect simplifies the code by maintaining default operations while adding custom logic.

Real-World Use Cases

  1. Security wrappers: Restrict access to sensitive properties.
  2. Logging and debugging: Track object changes.
  3. API data validation: Ensure strict rules for API data.

Conclusion

Metaprogramming with Proxies and Reflect enables developers to dynamically control and modify application behavior. Master these tools to elevate your JavaScript expertise.

Happy coding!

JavaScript Metaprogramming Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • An Introduction to Object Mutation in JavaScript
  • A Comprehensive Guide To Working With JSON in JavaScript
  • JavaScript's Secret Weapon: Unraveling the Mysteries of Proxies
  • Modern Web Development With ReactJS: Best Practices and Tips

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook