JavaScript Meta Programming
Metaprogramming
Metaprogramming is writing code that can:
- Inspect Object Properties
- Intercept Operations
- Control Operations
- Modify Objects
- Modify Properties
- Modify Functions
- Modify classes
- Generate code dynamically
Easy Explanation
Normally, code handles data.
With metaprogramming, code handles code.
Inspecting Object Properties
With the method Object.keys() you can inspect object properties.
Object.keys() is a simple example of metaprogramming.
Example
This code is analyzing another piece of code (an object):
const user = { name: "Jan", age: 40 };
const myArr = Object.keys(user);
Try it Yourself »
Proxies For Metaprogramming
A Proxy can be used to intercept property operations like reading or writing.
Example
Log changes to all property values:
// Create an Object
const user = { name: "Jan", age: 40 };
//Create a Proxy
const proxy = new Proxy(user, {
set(target, property, value) {
log(property + "; " + value);
return target[property];
}
});
proxy.name = "John";
proxy.age = 45;
proxy.name = "Paul";
Try it Yourself »
Object Property Descriptors
Object.defineProperty() can modify how properties behave:
Object.defineProperty(obj, "name", {
get() { return "Secret"; }
});
Dynamic Functions
JavaScript can generate functions at runtime:
const fn = new Function("a", "b", "return a + b");
Why Metaprogramming
| What | How |
|---|---|
| Validation | Restrict values that can be set |
| Logging | Intercept an operation using a Proxy |
| Debugging | Display value changes using a Proxy |
| Reactive frameworks | Vue, MobX, and Svelte use metaprogramming to detect state changes. |
| ORM / database mapping | Automatically wrap objects and creates fields based on database schema. |
| Dynamic APIs | Create functions or object structures at runtime |