Skip to Content
JavaScriptBasicObjects & Arrays

Objects & Arrays 🧊

JavaScript organizes data with objects (key/value) and arrays (ordered lists).

1) Creating Objects 🏗️

const user = { id: 1, name: "Aisha", contact: { email: "aisha@example.com" } }; user.role = "admin";
  • Braces {} create an object; add properties directly.
  • Use bracket notation for dynamic keys: user[dynamicKey] = value;.

2) Arrays & Helper Methods 🧮

const todos = ["buy milk", "fold laundry"]; todos.push("call mom");
  • Common methods:
    • push/pop, shift/unshift mutate arrays.
    • map, filter, reduce, find, some, every return new arrays or values.
const completed = todos.filter(todo => todo.includes("laundry"));

3) Destructuring 🎁

const { name, contact: { email } } = user; const [firstTodo, ...rest] = todos;
  • Pull out properties/values into variables succinctly.
  • Provide defaults: const { theme = "light" } = settings;

4) Spread & Rest 🌊

  • Spread copies elements:
const cloned = { ...user, active: true }; const merged = [...todos, "read"];
  • Rest packs the “remaining” items into an array/object:
function logFirstAndRest(first, ...restItems) { console.log(first, restItems); }

5) Immutable Mindset 🧠

  • Prefer creating new objects/arrays over mutating existing ones to keep state predictable.
  • Use structured cloning (structuredClone(obj)) or JSON.parse(JSON.stringify(obj)) (with caveats) for deep copies.

Key Takeaways ✅

  • Objects model named data; arrays handle ordered collections.
  • Destructuring and spread/rest keep code concise and expressive.
  • Array helper methods encourage declarative operations over loops.

Recap 🔄

Once you’re fluent with object literals, array helpers, and destructuring/spread, you can shape data cleanly and feed it directly into UI components or APIs.

Last updated on