JavaScript - Objects

Overview

Estimated time: 30–40 minutes

Objects are key–value collections. Create them with literals, read/write properties, and add methods. You'll also see handy utilities like Object.keys, Object.entries, and Object.assign.

Learning Objectives

  • Create objects with literals and Object.create.
  • Access properties (dot/bracket), computed keys, and methods.
  • Use common utilities: keys, values, entries, assign, fromEntries.

Prerequisites

Object literal and property access

const user = { id: 1, name: 'Ada' };
user.name;        // 'Ada' (dot access)
user['name'];     // 'Ada' (bracket)

const key = 'role';
user[key] = 'admin';         // computed key
user.greet = function(){ return `Hi ${this.name}`; };

Shorthand and computed keys

const name = 'Lin';
const role = 'editor';
const profile = { name, role, ['is-' + role]: true };

Enumerating properties

Object.keys(user);      // ['id','name','role','greet']
Object.values(user);    // [1,'Ada','admin', function]
Object.entries(user);   // [['id',1], ['name','Ada'], ...]

const pairs = [['x',10], ['y',20]];
Object.fromEntries(pairs); // { x:10, y:20 }

Copying/merging objects

const u1 = { id: 1, tags: ['a'] };
const u2 = { ...u1, name: 'Ada' };      // shallow copy via spread
const u3 = Object.assign({}, u1, { name: 'Ada' });

Common Pitfalls

  • Spread/assign are shallow: nested objects/arrays are shared references.
  • Using in includes inherited keys; for own keys use Object.hasOwn(obj, key) or Object.prototype.hasOwnProperty.call(obj, key) in older environments.

Checks for Understanding

  1. What’s the difference between dot and bracket property access?
  2. Why is Object.assign considered a shallow copy?
Show answers
  1. Dot requires a valid identifier known at author time; bracket works with strings or computed keys at runtime.
  2. It copies only the top-level properties; nested objects/arrays are still shared references.

Exercises

  1. Write a function that returns an object from an array of key/value pairs using Object.fromEntries.
  2. Clone an object with nested arrays and prove why a shallow copy is not enough.