0 day streak
javascript / intermediate
Snippet

Meta-Programming with Reflect

The Reflect API provides methods for interceptable JavaScript operations. Unlike the Object class, Reflect methods return a boolean to indicate success and offer a more consistent way to handle property definition and inspection.

snippet.js
javascript
1
2
3
4
5
6
7
const user = { id: 42 };
Reflect.defineProperty(user, 'hidden', {
value: 'secret',
enumerable: false
});
console.log(Reflect.has(user, 'id'));
console.log(Reflect.ownKeys(user));
Breakdown
1
Reflect.defineProperty(user, 'hidden', { ... });
Defines a new property on the object, returning true if successful.
2
enumerable: false
Makes the property invisible during standard loops like for...in.
3
Reflect.has(user, 'id');
Checks if the property exists on the object or its prototype chain.
4
Reflect.ownKeys(user);
Returns an array of all own property keys, including non-enumerable ones.