Code Logo

Meta-Program with Reflect API

Published at25 Jul 2026
JavaScript Functions Hard 0 views
Like0

Write a JavaScript function that uses Reflect.get() to read a property from an object and Reflect.set() to write a property, returning the value before modification. The Reflect API provides methods for interceptable JavaScript operations that correspond to the Proxy traps.

The Reflect API, introduced in ES6, is a built-in object with static methods that mirror Proxy traps. Reflect.get(target, propertyKey) is equivalent to the bracket notation target[propertyKey] but returns undefined and can be used with Receiver for inheritance. Reflect.set(target, propertyKey, value) sets a property and returns a boolean indicating success, unlike the assignment operator which silently fails in some cases.

Reflect methods are the programmatic counterparts to internal language operations. They are useful for forwarding Proxy traps to the target object, implementing meta-programming patterns, and performing operations that would otherwise require try/catch or typeof checks. The Reflect API is unique to JavaScript among mainstream languages.

Time complexity is O(1) for both Reflect.get() and Reflect.set(). Space complexity is O(1). Reflect methods have the same performance characteristics as the corresponding language operations they mirror.

Edge cases include non-existent properties (Reflect.get returns undefined), read-only properties (Reflect.set returns false), and ensuring the correct receiver is used for inherited getters.

Example Input & Output

Example 1
Input
{"name":"Alice"},"name","Bob"
Output
Alice
Explanation

Old name is Alice

Example 2
Input
{"z":42},"z",-1
Output
42
Explanation

Old z is 42, set to -1

Example 3
Input
{"x":10},"x",0
Output
10
Explanation

Old value of x is 10

Example 4
Input
{"val":100},"val",200
Output
100
Explanation

Old val is 100

Example 5
Input
{"a":1},"a",99
Output
1
Explanation

Old value of a is 1, set to 99

Algorithm Flow

Recommendation Algorithm Flow for Meta-Program with Reflect API
Recommendation Algorithm Flow for Meta-Program with Reflect API

Solution Approach

function solution(obj, key, val) {
  var old = Reflect.get(obj, key);
  Reflect.set(obj, key, val);
  return old;
}

Best Answers

javascript - Approach 1
function solution(obj, key, val) {
  var old = Reflect.get(obj, key);
  Reflect.set(obj, key, val);
  return old;
}