# Object Operations

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Objects
Source: https://www.devtutorials.ai/learn/javascript/objects/object-operations

> Nested objects and safe reads with ?., destructuring with defaults, copying and combining with spread, collecting leftovers with rest, shallow versus deep copies, computed keys, and immutable updates with const and Object.freeze.

## What Are Object Operations?

**Object operations** = short ways to take values **out** of an object, or put them **into** a new one.

- **Nested objects** and `?.` for data inside data.
- **Destructuring** to pull properties into variables.
- **Spread** `...` to copy and combine; **rest** `...` to collect what is left.
- **Computed keys** `[name]` to build keys from variables.

**Simple lesson:** you rarely change objects by hand. You read parts out, and build new objects from old ones.

### A Real-World Example

An order holds a customer, who holds an address: `order.customer.address.city`.
When the customer changes the city, the shop makes `{ ...order, customer: { ...order.customer, city: "Madurai" } }`.
The old order stays unchanged, so the page can compare old and new.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="Nested boxes: order contains customer, which contains address with city Chennai. A dot path walks inward one box at a time." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="30" y="30" width="500" height="120" rx="10" fill="#eff6ff" stroke="#2563eb" />
    <text x="45" y="52" fontSize="12" fill="#1e40af">order</text>
    <rect x="150" y="50" width="360" height="85" rx="10" fill="#fefce8" stroke="#ca8a04" />
    <text x="165" y="72" fontSize="12" fill="#854d0e">customer</text>
    <rect x="300" y="70" width="190" height="50" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="395" y="92" textAnchor="middle" fontSize="12" fill="#166534">address</text>
    <text x="395" y="110" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#166534">city: "Chennai"</text>
    <circle r="7" cy="100" fill="#dc2626"><animate attributeName="cx" values="60;180;330;460" keyTimes="0;0.33;0.66;1" calcMode="discrete" dur="3s" repeatCount="indefinite" /></circle>
    <text x="280" y="170" textAnchor="middle" fontSize="12" fontFamily="monospace" fill="#475569">order.customer.address.city</text>
  </svg>
  <figcaption>Each dot steps one box deeper.</figcaption>
</figure>

## What You Will Learn

1. Reading nested objects safely with `?.` and `??`.
2. Destructuring, renaming and default values.
3. Spread to copy and combine; rest to collect the remaining keys.
4. Shallow copies versus deep copies (`structuredClone()`).
5. Computed property names.

## Nested Objects

### Objects inside objects

A **nested object** is an object stored as a property value of another object.

```js runnable title="An order that holds a customer, who holds an address"
const order = {
  id: 5012,
  total: 1840,
  customer: {
    name: "Asha",
    address: {
      city: "Chennai",
      pincode: "600040",
    },
  },
};

console.log(order.customer);
```

Expected output:

```text
{
  "name": "Asha",
  "address": {
    "city": "Chennai",
    "pincode": "600040"
  }
}
```

### Accessing nested properties

Use one dot per level, read from left to right.

```js runnable title="One dot per level"
const order = {
  id: 5012,
  customer: { name: "Asha", address: { city: "Chennai", pincode: "600040" } },
};

console.log(order.customer.name);
console.log(order.customer.address.city);
console.log(order["customer"]["address"]["pincode"]);
```

Expected output:

```text
Asha
Chennai
600040
```

If a middle level is missing, the chain breaks with an error:

```js runnable expect-error title="A missing middle level stops the whole chain"
const order = { id: 5013, customer: { name: "Ravi" } };

console.log(order.customer.address.city);
```

`reading 'city'` means the value **before** `.city` was `undefined`.
**Optional chaining** `?.` stops safely instead, and `??` gives a fallback:

```js runnable title="?. stops safely at a missing level"
const order = { id: 5013, customer: { name: "Ravi" } };

console.log(order.customer.address?.city);
console.log(order.customer.address?.city ?? "No address on file");
```

Expected output:

```text
undefined
No address on file
```

In `Cannot read properties of undefined (reading 'x')`, the missing piece is always the one just left of `.x`.

## Destructuring

**Destructuring** = list the keys in `{ }` on the left of `=`, and get one variable per key.

### Basic destructuring

`{ price: cost }` takes `price` but names the variable `cost`.

```js runnable title="Three lines become one"
const product = { title: "Desk Lamp", price: 1299, brand: "Lumo" };

const title = product.title;
const price = product.price;
console.log(title, price);

const { brand, price: cost } = product;
console.log(brand, cost);
```

Expected output:

```text
Desk Lamp 1299
Lumo 1299
```

**Why "destructuring"?** It takes a structure apart into separate variables.

### Default values

`{ currency = "INR" }` uses `"INR"` only when the key is missing or `undefined`. `null` is a real value, so it stays.

```js runnable title="A default fills in only when the value is undefined"
const settings = { theme: "dark", fontSize: undefined, language: null };

const { theme = "light", currency = "INR", fontSize = 16, language = "en" } = settings;

console.log(theme);
console.log(currency);
console.log(fontSize);
console.log(language);
```

Expected output:

```text
dark
INR
16
null
```

Defaults do not replace `null`. Use `language ?? "en"` when a value might be `null`.

## Spread & Rest

Both use `...`, but they do opposite jobs: **spread** spills properties out; **rest** gathers them in.

### Copying properties

`{ ...product }` makes a new object with the same properties. Add changes after it.

```js runnable title="A copy, and a copy with one change"
const product = { title: "Desk Lamp", price: 1299 };

const copy = { ...product };
const onSale = { ...product, price: 999 };

console.log(copy);
console.log(onSale);
console.log(product.price);
console.log(copy === product);
```

Expected output:

```text
{
  "title": "Desk Lamp",
  "price": 1299
}
{
  "title": "Desk Lamp",
  "price": 999
}
1299
false
```

### Combining objects

Spread several objects into one. When a key repeats, the **last** one wins. So spread defaults first, user choices last.

```js runnable title="The last spread wins"
const defaults = { theme: "light", fontSize: 16, currency: "INR" };
const userChoices = { theme: "dark", fontSize: 18 };

console.log({ ...defaults, ...userChoices });
console.log({ ...userChoices, ...defaults });
```

Expected output:

```text
{
  "theme": "dark",
  "fontSize": 18,
  "currency": "INR"
}
{
  "theme": "light",
  "fontSize": 16,
  "currency": "INR"
}
```

### Collecting remaining properties

`const { password, ...safeUser } = user` takes `password` out and gathers the rest into `safeUser`. `user` itself does not change.

```js runnable title="Name the ones you want, collect the rest"
const user = { name: "Meera", email: "meera@example.com", password: "s3cret", city: "Kochi" };

const { password, ...safeUser } = user;

console.log(safeUser);
console.log("password" in safeUser);
console.log("password" in user);
```

Expected output:

```text
{
  "name": "Meera",
  "email": "meera@example.com",
  "city": "Kochi"
}
false
true
```

## Object Copying

`const b = a` does not copy. Both names point to the **same** object.

```js runnable title="Assignment shares one object between two names"
const original = { name: "Kiran", points: 40 };
const sameOne = original;

sameOne.points = 90;

console.log(original.points);
console.log(sameOne === original);
```

Expected output:

```text
90
true
```

### Shallow copy

Spread makes a new **outer** object, but nested objects are still **shared**. That is a **shallow copy**.

```js runnable title="Spread copies the top level and shares everything nested"
const order = { id: 5012, status: "packed", customer: { name: "Asha", city: "Chennai" } };
const copy = { ...order };

copy.status = "shipped";
copy.customer.city = "Madurai";

console.log(order.status);
console.log(order.customer.city);
console.log(copy.customer === order.customer);
```

Expected output:

```text
packed
Madurai
true
```

A **deep copy** copies every level. `structuredClone()` does it:

```js runnable title="structuredClone copies every level"
const order = { id: 5012, customer: { name: "Asha", city: "Chennai" } };
const deep = structuredClone(order);

deep.customer.city = "Madurai";

console.log(order.customer.city);
console.log(deep.customer.city);
console.log(deep.customer === order.customer);
```

Expected output:

```text
Chennai
Madurai
false
```

`{ ...obj }` is enough for top-level changes. For nested changes, copy that part too (`{ ...order, customer: { ...order.customer, city } }`), or use `structuredClone()`.

## Computed properties

Put a variable or expression in `[ ]` to use its **value** as the key: `{ [field]: "Pune" }`.

```js runnable title="The key comes from a variable"
const field = "city";
const plain = { field: "Pune" };
const computed = { [field]: "Pune" };

console.log(plain);
console.log(computed);

const month = "sep";
const sales = { [month + "Total"]: 48200 };
console.log(sales);
```

Expected output:

```text
{
  "field": "Pune"
}
{
  "city": "Pune"
}
{
  "sepTotal": 48200
}
```

Great for counting by category. `counts[status] ?? 0` starts each new key at 0:

```js runnable title="Counting orders by status with a computed key"
const statuses = ["shipped", "pending", "shipped", "cancelled", "shipped"];
let counts = {};

for (const status of statuses) {
  counts = { ...counts, [status]: (counts[status] ?? 0) + 1 };
}

console.log(counts);
```

Expected output:

```text
{
  "shipped": 3,
  "pending": 1,
  "cancelled": 1
}
```

## Immutable Updates

**Immutable update** = make a new object or array with the change, and leave the original alone. It keeps old versions for "undo", and lets a page see that something changed (`old !== new`).

- Objects: `{ ...obj, key: value }`. Arrays: `[...arr, item]`, `filter`, `map`, `toSorted()`, `with()`.
- `const` only stops reassignment. `Object.freeze(obj)` stops changes, but only at the top level.

```js runnable title="const versus Object.freeze, and an undo history"
const cart = { owner: "Asha", items: [] };
cart.items.push("Notebook");
console.log("const object changed:", cart.items.join(", "));

const order = Object.freeze({ id: 101, status: "pending", address: { city: "Pune" } });
order.status = "shipped";
order.address.city = "Chennai";
console.log("frozen status:", order.status, "| nested city:", order.address.city);

const history = [{ items: [] }];
const add = (item) => history.push({ ...history.at(-1), items: [...history.at(-1).items, item] });
add("Pen");
add("Bag");
history.pop();
console.log("after undo:", history.at(-1).items.join(", "), "| versions kept:", history.length);
```

Expected output:

```text
const object changed: Notebook
frozen status: pending | nested city: Chennai
after undo: Pen | versions kept: 2
```

## Object Operations on a Web Page

The form builds a new order with spread and a computed key. The old order is never changed, so both can be shown.

```js runnable preview="order-form" title="Building an updated order with spread"
const order = { id: 101, customer: { name: "Asha" }, items: { M: 1 } };
const form = document.querySelector("#order");
const result = document.querySelector("#result");

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const name = document.querySelector("#customer").value || order.customer.name;
  const size = document.querySelector("#size").value;
  const qty = Number(document.querySelector("#qty").value);

  const updated = {
    ...order,
    customer: { ...order.customer, name },
    items: { ...order.items, [size]: (order.items[size] ?? 0) + qty },
  };

  const { customer: { name: who }, items } = updated;
  result.textContent = `${who}: ${JSON.stringify(items)} (old order still ${JSON.stringify(order.items)})`;
  console.log("same object?", updated === order, "| shared customer?", updated.customer === order.customer);
});
```

Pick size **L**, quantity 2, and press **Place order**. The new order has `L: 2`; the old one still has only `M: 1`.

**Easy way to remember:** `...` on the **right** of `=` spreads out (copy). `...` on the **left** of `=` gathers up (rest).

## TL;DR

- Read deep values with dots; guard missing levels with `?.` and `??`.
- `const { a, b: renamed, c = 1 } = obj` pulls out variables with a rename and a default.
- `{ ...a, ...b }` copies and merges; the last key wins.
- `const { x, ...rest } = obj` collects the other keys.
- Spread is shallow; `structuredClone()` is deep. `{ [key]: value }` builds keys.

## Try this

In **Combining objects**, add `const campaign = { theme: "festive" };` and spread it last. `theme` becomes `"festive"`, and `fontSize` stays `18`.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `customer.address.city` with no address | Missing levels give `undefined` | Use `address?.city` | `Cannot read properties of undefined` |
| `{ language = "en" }` when it is `null` | Defaults replace `null` | Only `undefined` | `language` stays `null` |
| `{ ...userChoices, ...defaults }` | Order does not matter | The last spread wins | User settings are lost |
| Editing nested data in a spread copy | Spread copies every level | It is shallow | The original changes too |
| `const copy = original` | `=` copies | `=` shares | Both change together |
| `{ field: value }` | It uses the variable | Use `{ [field]: value }` | A key named "field" |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `order.customer.address.city` | read a value several levels down |
| `order.customer.address?.city` | stop with `undefined` if `address` is missing |
| `const { title, price } = product` | copy two properties into variables |
| `const { price: cost } = product` | copy `price` into a variable called `cost` |
| `const { currency = "INR" } = settings` | use a default when the value is `undefined` |
| `{ ...product }` | a shallow copy of an object |
| `{ ...defaults, ...choices }` | combine objects, and the later one wins |
| `const { password, ...rest } = user` | collect every other property into `rest` |
| `structuredClone(object)` | a deep copy of every level |
| `{ [key]: value }` | a computed property whose key comes from an expression |

</div>

## Exercises

## What to Remember

- `?.` keeps nested reads safe.
- Destructure to read, spread to copy and merge, rest to leave things out.
- Shallow copies share nested objects.

Next: **Collections**. `Map` for lookups with any type of key, and `Set` for unique values.
