Lesson 88 – JavaScript Reflect API
The Reflect
API was introduced in ES6 to provide methods for interceptable JavaScript operations. It works hand-in-hand with Proxy
, and provides a standardized way to perform object operations that were previously done in less elegant ways.
Why Reflect?
- To make operations like
get
,set
,delete
, etc., more declarative and functional. - To improve code consistency and avoid direct manipulation of object internals.
- To provide default behavior for traps in Proxy objects.
Core Reflect Methods
Here are some of the most commonly used methods:
const person = {
name: "John",
age: 30,
};
// get a property
console.log(Reflect.get(person, "name")); // John
// set a property
Reflect.set(person, "age", 31);
console.log(person.age); // 31
// check if a property exists
console.log(Reflect.has(person, "name")); // true
// delete a property
Reflect.deleteProperty(person, "age");
console.log(person); // { name: 'John' }
Using Reflect with Proxy
When writing proxy handlers, it's recommended to use Reflect
methods to maintain default behavior:
const user = {
username: "coder123",
};
const handler = {
get(target, prop) {
console.log(`Getting property: ${prop}`);
return Reflect.get(target, prop); // default behavior
},
};
const proxy = new Proxy(user, handler);
console.log(proxy.username); // logs "Getting property: username" then "coder123"
More Useful Reflect Methods
Method | Description |
---|---|
Reflect.get(target, propertyKey) |
Gets the property value |
Reflect.set(target, propertyKey, value) |
Sets the property value |
Reflect.has(target, propertyKey) |
Checks if property exists |
Reflect.deleteProperty(target, propertyKey) |
Deletes a property |
Reflect.ownKeys(target) |
Returns all property keys (including symbols) |
Reflect.defineProperty(target, key, descriptor) |
Defines a new property |
Reflect.getOwnPropertyDescriptor(target, key) |
Gets property descriptor |
Try Your Hand
const book = {
title: "JavaScript Mastery",
pages: 400,
};
Reflect.set(book, "author", "Jane Doe");
console.log(book);
const hasPages = Reflect.has(book, "pages");
console.log("Has pages:", hasPages);
Reflect.deleteProperty(book, "pages");
console.log(book);
Summary
- The
Reflect
API provides a functional way to perform object operations. - It works well with Proxy to provide default behaviors.
- Reflect methods improve readability and consistency in code.