Proxy Object in JavaScript

Level 4328 keystrokes

Uses Proxy to intercept and customize object property access and assignment.

JavaScript code

// Define the original object to be wrapped
1const target = { name: "Alice", age: 25 };
2
// Handler object contains trap functions
3const handler = {
// get trap intercepts property reads
4 get(obj, prop) {
// Return the value if property exists, otherwise "Not found"
5 return prop in obj ? obj[prop] : "Not found";
6 },
// set trap intercepts property assignments
7 set(obj, prop, value) {
// Validation: reject negative ages
8 if (prop === "age" && value < 0) return false;
// Otherwise, set the property normally
9 obj[prop] = value;
// Return true to indicate success
10 return true;
11 }
12};
13
// Create the Proxy wrapping the target with the handler
14const proxy = new Proxy(target, handler);
// Existing property returns value
15console.log(proxy.name);
// Non-existing property returns "Not found"
16console.log(proxy.city);

Output

Alice
Not found
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ;× 9
  • =× 7
  • ,× 6
  • "× 6
  • (× 6
  • )× 6
  • .× 4
  • {× 4
  • }× 4
  • :× 3

More JavaScript examples at level 4

← JavaScript typing practice