JavaScript - Object Properties & Methods

Overview

Estimated time: 35–45 minutes

Properties have descriptors (writable, enumerable, configurable). Learn to inspect and define them, and to use core utilities like Object.hasOwn, Object.keys/values/entries, Object.assign, Object.freeze, and more.

Learning Objectives

  • Inspect and define property descriptors.
  • Work with own vs inherited properties.
  • Use freezing/sealing and copying utilities safely.

Prerequisites

Descriptors

const user = { id: 1, name: 'Ada' };
const d = Object.getOwnPropertyDescriptor(user, 'name');
// { value: 'Ada', writable: true, enumerable: true, configurable: true }

Object.defineProperty(user, 'id', {
  value: 1,
  writable: false,
  enumerable: false,
  configurable: false
});

Own vs inherited properties

const obj = Object.create({ inherited: 1 });
obj.own = 2;
Object.hasOwn(obj, 'own');       // true
Object.hasOwn(obj, 'inherited'); // false
'inherited' in obj;              // true (walks prototype chain)

Copying and freezing

const src = { a: 1 };
const dst = Object.assign({}, src, { b: 2 }); // { a:1, b:2 }

const settings = Object.freeze({ theme: 'dark' });
// settings.theme = 'light'; // no effect; throws in strict mode

Other utilities

Object.seal(obj);              // can't add/remove props; can change writable ones
Object.preventExtensions(obj); // can't add new props
Object.getOwnPropertyNames(obj);
Object.getOwnPropertySymbols(obj);

Common Pitfalls

  • Object.defineProperty defaults to non-writable, non-enumerable, non-configurable when you omit flags.
  • for...in iterates inherited enumerable props; prefer Object.keys or guard with Object.hasOwn.

Exercises

  1. Define a non-enumerable, read-only property id and verify it doesn’t appear in Object.keys.
  2. Freeze a configuration object and attempt to modify it under strict mode to see the thrown error.