0Pricing
JavaScript Academy · Lesson

get and set Traps

Customize property reads and writes.

get and set Traps is a free JavaScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The get and set Traps

The get and set traps are the most-used proxy hooks. They intercept reading and writing properties, letting you transform values, validate input, or log access.

get Trap Signature

get(target, property, receiver) runs on every property read. Return whatever you want the caller to see.

const proxy = new Proxy({ price: 10 }, {
  get(target, prop) {
    return target[prop];
  }
});

console.log(proxy.price);

Default Values via get

A get trap can supply a fallback for missing properties instead of returning undefined.

const proxy = new Proxy({ a: 1 }, {
  get(target, prop) {
    return prop in target ? target[prop] : 0;
  }
});

console.log(proxy.a);
console.log(proxy.missing);

Transforming Read Values

The get trap can reshape values on the way out, for example uppercasing strings.

const proxy = new Proxy({ name: 'ada' }, {
  get(target, prop) {
    const value = target[prop];
    return typeof value === 'string' ? value.toUpperCase() : value;
  }
});

console.log(proxy.name);

set Trap Signature

set(target, property, value, receiver) runs on every write. It must return true for success, otherwise strict mode throws.

const proxy = new Proxy({}, {
  set(target, prop, value) {
    target[prop] = value;
    return true;
  }
});

proxy.x = 5;
console.log(proxy.x);

Validation in set

The classic use of a set trap is validation: reject invalid values before they reach the target.

const person = new Proxy({}, {
  set(target, prop, value) {
    if (prop === 'age' && (typeof value !== 'number' || value < 0)) {
      throw new TypeError('age must be a non-negative number');
    }
    target[prop] = value;
    return true;
  }
});

person.age = 30;
console.log(person.age);
try { person.age = -5; } catch (e) { console.log(e.message); }

Coercing Values in set

Beyond rejecting, a set trap can normalize input, for example trimming strings before storing.

const proxy = new Proxy({}, {
  set(target, prop, value) {
    target[prop] = typeof value === 'string' ? value.trim() : value;
    return true;
  }
});

proxy.name = '   Ada   ';
console.log('[' + proxy.name + ']');

Logging Both Operations

Combine get and set to trace every access. This is invaluable for debugging how an object is used.

const proxy = new Proxy({ v: 1 }, {
  get(target, prop) {
    console.log('GET ' + prop);
    return target[prop];
  },
  set(target, prop, value) {
    console.log('SET ' + prop + ' = ' + value);
    target[prop] = value;
    return true;
  }
});

proxy.v = 42;
console.log(proxy.v);

Enforcing Read-Only

A set trap that always rejects writes turns a proxy into a read-only view of its target.

const readonly = new Proxy({ pi: 3.14 }, {
  set() {
    console.log('writes are blocked');
    return false;
  }
});

try {
  'use strict';
  readonly.pi = 0;
} catch (e) {
  console.log(e.name);
}
console.log(readonly.pi);

Symbol Keys and Internals

Traps fire for symbol keys too. Be careful: logging every property including internal symbols can be noisy, so filter when needed.

const proxy = new Proxy({ a: 1 }, {
  get(target, prop) {
    if (typeof prop === 'string') console.log('reading ' + prop);
    return target[prop];
  }
});

console.log(proxy.a);

Why get and set Matter

Together these traps enable validation, computed properties, defaults, logging, and reactivity, all without modifying the target. But manually writing target[prop] = value inside traps has edge cases. The Reflect API, covered next, handles them correctly.

const tracked = new Proxy({ total: 0 }, {
  set(target, prop, value) {
    console.log(prop + ' changed to ' + value);
    target[prop] = value;
    return true;
  }
});
tracked.total = 100;
console.log(tracked.total);

Quick Check

What must a set trap return to indicate a successful assignment?

Recap: get and set Traps

You learned the core proxy traps:

  • get(target, prop, receiver) intercepts reads; return any value.
  • set(target, prop, value, receiver) intercepts writes; return true on success.
  • Use them for defaults, transforms, validation, and logging.
  • For correct internal handling inside traps, use Reflect, covered next.

Frequently asked questions

Is the “get and set Traps” lesson free?

Yes — the full text of “get and set Traps” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “get and set Traps”?

Customize property reads and writes. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start JavaScript Academy?

No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “get and set Traps” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this JavaScript Academy lesson?

Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Creating a Proxy
  2. get and set Traps
  3. The Reflect API
  4. Practical Proxy Use Cases
← Back to JavaScript Academy