JavaScript: Objects

Group related data and behavior with key–value pairs and methods.

Object literals

const user = {
  id: 1,
  name: 'Ahbab',
  email: 'a@example.com',
  greet() {
    return `Hi, ${this.name}!`;
  }
};

Access & computed properties

user.name;          // dot
user['email'];      // bracket (useful with dynamic keys)
const key = 'id';
user[key];          // 1

Destructuring & defaults

const { name, email = 'n/a' } = user;
const { id: userId } = user; // rename

Copy/merge (shallow)

const a = { x: 1, y: 2 };
const b = { y: 3, z: 4 };

const merged = { ...a, ...b };           // { x:1, y:3, z:4 }
const copy = { ...a };                    // { x:1, y:2 }
const assigned = Object.assign({}, a, b); // same idea

Practice

  1. Create a course object with title, hours, and tags.
  2. Write a method on it that returns a summary string.
  3. Use destructuring to pull out title and hours.

Next up

Quick Check

Which operator checks whether a property exists on an object?