← Back to Angular, page 8

angular-0157 · Easy fresher

Why does Angular code prefer creating new arrays and objects instead of changing them in place?

Angular compares references to find out what changed. If you push into an array or edit an object in place, the reference stays the same, so OnPush components, signals and pure pipes may not notice. Creating a new array or object (spread, map, filter) changes the reference and makes the change visible.

Full answer

In JavaScript an array or object variable holds a reference (an address), not the data itself. Many Angular features check "is this the same reference as before?" because it is fast: one comparison with ===, not a deep comparison of every item.

Where the reference check matters:

  1. Inputs of OnPush components. The child updates only when the input reference changes. students.push(newStudent) keeps the same array, so the child does not update. students = [...students, newStudent] gives a new reference.
  2. Signals. A signal notifies readers when the new value is not equal (by default, ===) to the old one. list.update(l => { l.push(x); return l; }) returns the same array, so nothing is notified. Use list.update(l => [...l, x]).
  3. Pure pipes. A pure pipe runs again only when its input reference changes.
  4. @for with track. Angular finds which items moved or were added by comparing the tracked keys.
  5. Store libraries (NgRx) rely on immutable updates for selectors to stay fast.

Immutable update patterns:

  • Add: [...list, item].
  • Remove: list.filter(x => x.id !== id).
  • Change one item: list.map(x => x.id === id ? { ...x, marks: 90 } : x).
  • Change an object: { ...student, marks: 90 }.
  • Sorting: [...list].sort(...) because sort changes the array in place. Newer methods toSorted, toSpliced and toReversed return copies.

Spread copies are shallow: only the first level is new. A nested object that you did not copy is still shared, which is usually fine, because it did not change.

Cost: copying large arrays on every key press is wasteful. For very large lists use pagination, virtual scroll or a library such as Immer. For small and medium lists the cost is negligible.

Mutation is not always a bug. In the default change detection mode, a mutation is seen on the next pass. Immutable updates matter when you use OnPush, signals and pure pipes, which modern Angular encourages.

typescript
export {};

interface Student {
  id: number;
  name: string;
  marks: number;
}

const original: Student[] = [
  { id: 1, name: 'Asha', marks: 70 },
  { id: 2, name: 'Ravi', marks: 55 },
];

// Mutation: same reference, so a reference check sees "no change".
const mutated = original;
mutated.push({ id: 3, name: 'Meena', marks: 88 });
console.log('mutated same reference:', mutated === original, mutated.length);

// New reference for each change.
const added = [...original, { id: 4, name: 'Imran', marks: 61 }];
const removed = added.filter((s) => s.id !== 2);
const updated = removed.map((s) => (s.id === 1 ? { ...s, marks: 95 } : s));
console.log('added new reference:', added !== original);
console.log('updated item is new:', updated[0] !== original[0], 'other item shared:', updated[1] === original[2]);

const sorted = [...updated].sort((a, b) => b.marks - a.marks);
console.log(sorted.map((s) => `${s.name}:${s.marks}`).join(' '));
console.log('original order untouched:', original.map((s) => s.id).join(','));

TypeScript 5.8 with Node 24. The script was run twice with identical output. It shows that a mutated array keeps the same reference, and a spread copy does not.

Key points

  • Angular checks references with `===`, not deep content.
  • Mutating in place keeps the reference, so OnPush inputs, signals and pure pipes may miss the change.
  • Use spread, `map`, `filter` and `toSorted` to create new values.
  • Spread is shallow. Avoid copying very large lists on every event.

Common mistakes

  • Using `push` on an array that is an OnPush input or inside a signal.
  • Sorting a shared array in place.
  • Assuming spread makes a deep copy.

Follow-ups

  • Why does `signal.update` with a mutation not notify?
  • How do you change one item in a list immutably?
  • When can you still mutate safely?

Tips

  • Contrast `push` with spread in one line each.
  • Explain "reference" as an address.
  • Mention that default change detection hides the problem.

Evaluation rubric

  • Explains reference equality and why it is used.
  • Gives immutable patterns for add, remove and update.
  • Understands the cost and limits of spread.