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 wrapped1const target = { name: "Alice", age: 25 };2 // Handler object contains trap functions3const handler = { // get trap intercepts property reads4 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 assignments7 set(obj, prop, value) { // Validation: reject negative ages8 if (prop === "age" && value < 0) return false; // Otherwise, set the property normally9 obj[prop] = value; // Return true to indicate success10 return true;11 }12};13 // Create the Proxy wrapping the target with the handler14const proxy = new Proxy(target, handler);// Existing property returns value15console.log(proxy.name);// Non-existing property returns "Not found"16console.log(proxy.city);Output
Alice Not found
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