Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

35 min

Reading, Updating and Copying Objects

Choose dot or bracket access

By the end of this lesson

  • Choose dot or bracket access
  • Distinguish a shared object from a copy

A preview must not change the original

A quote preview changes a product price from 20 to 18. The catalog must remain unchanged. Would assigning preview = product create an independent copy?

const product = { name: "Notebook", price: 20 };
const field = "price";
console.assert(product[field] === 20);
const preview = { ...product, price: 18 };
console.assert(preview.price === 18);
console.assert(product.price === 20);

Dot notation uses a fixed property name. Bracket notation evaluates an expression to choose the key. product.field looks for a property literally named field; product[field] uses the value "price".

Object spread copies properties into a new object. Later properties override earlier ones, so price: 18 comes after the spread. This is a shallow copy, not a recursive clone.

Guided mutation trace

const original = { collected: false };
const alias = original;
alias.collected = true;
console.assert(original.collected === true);

Both names refer to the same object. Const prevents reassigning original, not modifying its properties. Reading a missing property returns undefined. That absence may reveal an invalid shape rather than a valid default.

Independent exercise

Create an uncollected order, then an updated copy with collected set to true. Verify both statuses and their shared reference value. Explain when intentional mutation might be acceptable.

Correction

Use { ...order, collected: true } for the copy; check order.collected remains false. Mutation may be appropriate when one operation intentionally owns the state change. A preview should not secretly change the catalog or history.

Review

Objects compare by identity with ===: two separately created objects with identical fields are not the same reference. Test the properties that represent behavior rather than assuming object equality compares every field.

Lesson complete?

Your progress is saved on this device.