CPCODELAB
JavaScript

Objects, Methods, and Destructuring

12 min read

Objects

Objects are collections of key-value pairs. Keys are strings (or Symbols); values can be any type including functions (in which case they are called methods).

javascript
const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2022,
  start() {
    console.log(this.make + " started!");
  }
};

car.make;         // dot notation
car["model"];     // bracket notation (useful with dynamic keys)
car.start();      // "Toyota started!"

// Object utility methods
Object.keys(car);    // ["make","model","year","start"]
Object.values(car);  // ["Toyota","Corolla",2022,fn]
Object.entries(car); // [["make","Toyota"], ...]
Object.assign({}, car, { year: 2023 }); // shallow clone + override

Destructuring

javascript
const { make, model, year = 2020 } = car;
// make = "Toyota", model = "Corolla", year = 2022

// Rename while destructuring
const { make: brand } = car;
// brand = "Toyota"

// Nested destructuring
const user = { name: "Alice", address: { city: "Paris" } };
const { address: { city } } = user;
// city = "Paris"

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first=1, second=2, rest=[3,4,5]

Spread and Rest

javascript
// Spread — expand iterable into individual elements
const a = [1, 2, 3];
const b = [...a, 4, 5]; // [1,2,3,4,5]

// Shallow clone an object
const original = { x: 1, y: 2 };
const clone = { ...original, z: 3 }; // { x:1, y:2, z:3 }

// Merge objects (later key wins)
const merged = { ...original, ...{ x: 99, w: 4 } };
// { x:99, y:2, w:4 }
Ready to test yourself?
Practice JavaScript— quiz & coding exercises