JavaScript
What is metaprogramming?
Learn how code manages other code and the reflection concept.
What is metaprogramming?
Metaprogramming is a style where code manages other code or inspects itself. Normally you write code and it runs; in metaprogramming, code reads another code's structure at runtime or changes its behavior.
This is often called reflection: a program learns about its own properties, types and methods. In JavaScript, typeof, Object.keys, Reflect, Proxy and Symbol are the tools for this.
In this group you will learn techniques that inspect, validate and wrap code.
Reflection tools
Reflection is a program reading its own structure: which properties exist, what type a value is, which methods are defined. JavaScript provides several tools for this.
typeof returns a value's type, Object.keys lists an object's property names, instanceof queries the prototype chain. The Reflect API gathers these into one consistent interface: Reflect.has, Reflect.get, Reflect.ownKeys.
Reflection only reads; it does not change behavior. Changing behavior starts with Proxy.
Exercise Inspect an object
Define a function describe(obj). Inside it, take the property names with Object.keys(obj) into a variable and log them with console.log. Then check the existence of a 'name' property with Reflect.has(obj, 'name') and log the result. Finally call describe({ name: 'Alex', age: 28 }).
Show example solution
function describe(obj) {
const keys = Object.keys(obj);
console.log(keys);
console.log(Reflect.has(obj, 'name'));
}
describe({ name: 'Alex', age: 28 });
Test yourself
-
Which is an example of metaprogramming?
const handler = { set(t,p,v){ if(p==='age' && v<0) throw new TypeError(); t[p]=v; return true; } };
- Validating and blocking an assignment with a Proxy
- Summing numbers in an array
- Taking the first three characters of a string
- Converting a string to uppercase
Show answer
Validating and blocking an assignment with a Proxy — Correct! A Proxy that validates assignments manages another code's behavior, so it is metaprogramming.
-
Match each tool to its purpose
- Reflect.has
- Property exists
- Object.keys
- List property names
- typeof
- Value type
- Proxy
- Wrap behavior
-
Property check with Reflect
const user = { name: 'Alex' };
const exists = ____;
console.log(exists);
Show answer
const user = { name: 'Alex' };
const exists = Reflect.has(user, 'name');
console.log(exists);
Next lesson: Validation with Proxy