Skip to the page

Objects, prototypes and classes · mid

Property descriptors, getters, setters, freeze and seal

Every property has a descriptor — either a data descriptor (value, writable) or an accessor descriptor (get, set) — plus enumerable and configurable flags, and freeze, seal and preventExtensions use these flags to lock an object shallowly.

The notes

What you must know

  • Object.getOwnPropertyDescriptor(obj, 'k') returns { value, writable, enumerable, configurable } or { get, set, enumerable, configurable }.
  • Properties made by assignment or a literal have every flag true. With Object.defineProperty, any flag you leave out defaults to false.
  • writable: false -> assignment is silently ignored in sloppy mode and throws TypeError in strict mode.
  • enumerable: false -> hidden from for...in, Object.keys, JSON.stringify and spread, but still readable.
  • configurable: false -> the property can't be deleted and its descriptor can't be changed (except writable true -> false).
  • Getters and setters: computed values, validation, lazy values. JSON.stringify calls getters and writes their values.
  • Object.preventExtensions: no new properties. Object.seal: also no deleting (configurable false). Object.freeze: also no writing (writable false). All three are shallow.

The red pen

Common traps: mistake → fix

  • Mistake: Object.freeze makes an object deeply immutable

    Fix: nested objects stay mutable.

  • Mistake: Writing to a frozen object always throws

    Fix: only in strict mode; sloppy mode ignores it silently.

  • Mistake: defineProperty defaults to writable, enumerable and configurable true

    Fix: they default to false.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are property descriptors?
  2. Compare freeze, seal and preventExtensions.
  3. How do you make a read-only property? What happens on write in strict vs sloppy mode?
  4. Give real use cases for getters and setters.
  5. Implement deepFreeze. Why do Redux Toolkit and Immer freeze state in development?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview