Skip to article content
FrontendXLesson 19 / 30

Getters, Setters and Property Descriptors

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

advanced · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Define computed properties with getters and setters.
  • Read and set property flags with Object.defineProperty.
  • Explain how freeze, seal and private fields protect state.

Overview

#

Accessors

A getter runs when a property is read and a setter runs when it is written. They look like properties to the caller but are functions underneath, which is useful for computed values and validation.

snippet.js
const circle = {
  radius: 2,
  get area() { return Math.PI * this.radius ** 2; }
};
console.log(circle.area.toFixed(2)); // 12.57

Descriptors

Every property has a descriptor with value, writable, enumerable and configurable, or with get and set instead of value and writable. Object.defineProperty sets these flags. A non-enumerable property is skipped by spread, Object.keys and for..in, and a non-configurable property cannot be redefined.

snippet.js
const obj = {};
Object.defineProperty(obj, 'id', { value: 1, enumerable: false });
console.log(Object.keys(obj).length); // 0

Protecting state

Object.freeze makes properties non-writable and non-configurable at the top level, Object.seal keeps them writable but prevents adding or removing, and preventExtensions only blocks new properties. All three are shallow. Class private fields, written with a leading hash, are enforced by the language and are the strongest form of encapsulation.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const o = {};
    Object.defineProperty(o, 'x', { value: 1, enumerable: false });
    o.y = 2;
    console.log(Object.keys(o).length, o.x);
    Choose the best answer
  2. Exercise 2Explain

    Explain the difference between a getter and a regular method.

    starter.text
    const o = { get v() { return 1; }, m() { return 1; } };

    Reveal the reference answer
    reference.text
    A getter is accessed like a property, without parentheses, and runs its body on every read. A method is called with parentheses and returns a value at that moment. The getter is convenient for computed values but hides that work is happening, so a getter that is expensive or has side effects surprises callers. I use a getter for cheap derived values and a method when the operation is costly or mutates state.

    Authored expected output: 1 1

    The answer should note syntax, per-read evaluation and the expectation that a getter is cheap and side-effect free.

  3. Exercise 3Implement

    Implement a `temperature` object whose celsius property is validated on write and whose fahrenheit is derived. Setting celsius to -300 should leave it at 0.

    starter.javascript
    const temperature = {
      _celsius: 0,
      // your code here
    };

    Reveal the reference answer
    reference.javascript
    const temperature = {
      _celsius: 0,
      get celsius() { return this._celsius; },
      set celsius(value) { this._celsius = Math.max(0, value); },
      get fahrenheit() { return this._celsius * 9 / 5 + 32; }
    };

    Authored expected output: 0 32

    The setter clamps the input before storing it, so an invalid write is neutralized. The fahrenheit getter derives its value from the stored celsius on each read.

  4. Exercise 4Debug

    This object is meant to store a value in a backing field but reading it throws a stack overflow. Find and fix the bug.

    starter.javascript
    const o = {
      get value() { return this.value; },
      set value(v) { this.value = v; }
    };
    o.value = 1;
    console.log(o.value);

    Reveal the reference answer
    reference.javascript
    const o = {
      get value() { return this._value; },
      set value(v) { this._value = v; }
    };
    o.value = 1;
    console.log(o.value);

    Authored expected output: 1

    The getter reads this.value, which calls the getter again forever. Storing under a different name such as _value breaks the recursion while keeping the public name.

  5. Exercise 5Test

    Write assertions that prove Object.freeze is shallow.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    const frozen = Object.freeze({ nested: { count: 1 } });
    frozen.nested.count = 2;
    assertEqual(frozen.nested.count, 2, 'nested object is still mutable');
    assertEqual(Object.isFrozen(frozen), true, 'top level is frozen');
    assertEqual(Object.isFrozen(frozen.nested), false, 'nested object is not frozen');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    freeze applies only to the object it is called on. Nested objects remain writable, so a deep freeze needs a recursive pass.

  6. Exercise 6Interview

    How do you hide internal state in a JavaScript class?

    Reveal the reference answer
    reference.text
    I use private class fields with a leading hash, because the language enforces them and they cannot be reached from outside. Before private fields I used a closure to capture the state, or a WeakMap keyed by the instance. I avoid naming conventions such as an underscore, which signal intent but do not prevent access, and I keep the public surface small so the internal shape can change freely.

    The answer should rank private fields, closures and WeakMaps as real encapsulation and reject underscore naming as enforcement.

Common misconceptions

#
  • A getter is stored as a value and recomputed only once.
  • Object.freeze deeply freezes nested objects.
  • Non-enumerable properties cannot be read.

Follow-up practice

#
  • javascript-foundations-metaprogramming
  • javascript-foundations-map-set-and-weak-collections

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.