Topic 06 / 15

Objects & Destructuring

~9 min read  //  JavaScript Series  //  Coding India

Object Literals

Objects are JS’s key-value structure — and the shape of every JSON payload:

const course = {
  title: "JavaScript Mastery",
  price: 199,
  tags: ["js", "web"],
  instructor: {
    name: "Digamber",
    channel: "Coding India",
  },
};

course.title                    // dot access
course["title"]                 // bracket access
const key = "price";
course[key]                     // bracket = dynamic keys
course.instructor.name          // nested
course.discount = 0.1;          // add a property
delete course.discount;         // remove one

Shorthand & Methods

const name = "Ravi", score = 82;

const player = {
  name,                          // shorthand for name: name
  score,
  describe() {                   // method shorthand
    return `${this.name}: ${this.score}`;
  },
};

Destructuring — Unpack in One Line

const { title, price } = course;
const { name: instructorName } = course.instructor;   // rename
const { level = "beginner" } = course;                 // default

// in function parameters — extremely common
function renderCard({ title, price, tags = [] }) {
  return `${title} — ₹${price} [${tags.join(", ")}]`;
}
renderCard(course);

Spread & Rest for Objects

const updated = { ...course, price: 149 };      // copy with one change
const merged = { ...defaults, ...userPrefs };   // right side wins

const { tags, ...withoutTags } = course;        // rest — everything else

The { ...obj, change } pattern is everywhere in React — it creates a new object instead of mutating, which is how UI state updates are detected. Note it’s a shallow copy: nested objects are still shared. For a deep copy use structuredClone(course).

Iterating Objects

Object.keys(course)       // ['title', 'price', 'tags', 'instructor']
Object.values(course)
Object.entries(course)    // [['title', '...'], ['price', 199], ...]

for (const [key, value] of Object.entries(course)) {
  console.log(key, "→", value);
}

// build an object from entries
Object.fromEntries([["a", 1], ["b", 2]])   // {a: 1, b: 2}

Checking Properties

"price" in course                 // true
course.missing ?? "default"      // safe fallback
course.instructor?.name          // optional chaining for deep access