MediumState & Immutability💻 Output Question

Updating array items immutably with map

💡

Hint

This is the canonical React pattern for updating an item in a list. Unchanged items keep their references — React.memo'd children won't re-render for those.

What does this output?

const todos = [
  { id: 1, text: 'Buy milk', done: false },
  { id: 2, text: 'Write code', done: false },
  { id: 3, text: 'Exercise', done: false },
];

// Toggle todo with id=2 as done
const updated = todos.map(todo =>
  todo.id === 2 ? { ...todo, done: true } : todo
);

console.log(todos[1].done);
console.log(updated[1].done);
console.log(todos[1] === updated[1]);
console.log(todos[0] === updated[0]);

Correct Output

false
true
false
true

Why this output?

Explanation: map creates a new array. The item with id=2 gets a spread copy with done:true — new reference. Items not matching return the SAME reference (no spread needed).

Key Insight: This is the canonical React pattern for updating an item in a list. Unchanged items keep their references — React.memo'd children won't re-render for those.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz