JavaScript From Zero · 18 min · 130 XP

Objects and destructuring

Group data in objects, read nested values safely, and update them without changing the original.

An object groups named values: const item = { id: "headlamp", price: 35, qty: 1 };. Read with a dot (item.price) or brackets when the name is in a variable (item[field]). A property that doesn't exist is undefined, and reading a property of undefined throws, which is the most common error in JavaScript.

javascript
const customer = { name: "Ada", address: { city: "Oslo" } };

customer.address.city            // "Oslo"
customer.billing?.city           // undefined (optional chaining: no crash)
const { name, address: { city } } = customer;   // destructuring
const { phone = "none" } = customer;             // with a default

Objects are passed by reference. const b = a doesn't copy anything; both names point to the same object, so changing b.qty changes a.qty too. To update something without changing the original, build a new object with spread: { ...item, qty: 3 }. Spread copies only one level deep, so update nested parts with spread too.

javascript
const cart = { owner: "Ada", items: [{ id: "a", qty: 1 }, { id: "b", qty: 2 }] };

const updated = {
  ...cart,
  items: cart.items.map((item) => (item.id === "a" ? { ...item, qty: 5 } : item)),
};
// cart is unchanged; updated has a new items array with a new "a" object

Loading your workspace…