MediumState & Immutability💻 Output Question

Array state — push mutates, spread does not

💡

Hint

React state updates need new references. For arrays: use [...arr, item] to add, arr.filter() to remove, arr.map() to update. Never push/splice/sort the state array directly.

What does this output?

const items = ['a', 'b'];

// Wrong — mutates original
const wrong = items;
wrong.push('c');

// Correct — new array
const correct = [...items, 'd'];

console.log(items.length);
console.log(items === wrong);
console.log(correct.length);
console.log(items === correct);

Correct Output

3
true
4
false

Why this output?

Explanation: wrong = items is same reference. push('c') mutates items — length becomes 3. [...items,'d'] creates new array with 4 items. items !== correct.

Key Insight: React state updates need new references. For arrays: use [...arr, item] to add, arr.filter() to remove, arr.map() to update. Never push/splice/sort the state array directly.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz