Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.6 — Proxy and Reflect
JavaScript · Example 2 of 3 ES2015+

Validation, defaults and negative indexes

Property keys always reach traps as strings (or symbols), so list[-1] arrives as the string "-1". Checking the type first matters: Number(symbol) would throw when the array is spread.

A Proxy wraps an object and lets you intercept basic operations on it (reading, writing, deleting, in, calling) with handler functions called traps; Reflect offers the default version of each operation, so a trap can add behaviour and then do the normal thing.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write readOnly(obj) that returns a proxy where reads work but any write or delete throws Error("read-only"). Show both behaviours.

02

Write a proxy env where reading a missing key throws ReferenceError("Unknown setting: <key>") instead of returning undefined, so typos are caught.

Explain it without notes

01

What is a Proxy and what is a trap? Give three traps and the operations they intercept.

02

Why is Reflect usually used inside traps?

03

How would you validate property values with a Proxy, and how does strict mode affect it?

04

Explain how a Proxy can make UI reactive, and what its limits are.

Validation, defaults and negative indexes ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Invalid value for age: -5
30
3 0
30 10 10 3