MediumState & Immutability💻 Output Question

Removing from array state with filter

💡

Hint

filter is the idiomatic React way to delete from array state. It returns a new array and never mutates. removed === items is false, so React will detect the change.

What does this output?

const items = [1, 2, 3, 4, 5];

// Remove item at index 2
const removed = items.filter((_, i) => i !== 2);

// Remove by value
const removedVal = items.filter(x => x !== 3);

console.log(items.length);   // original unchanged?
console.log(removed.join(','));
console.log(removedVal.join(','));
console.log(removed === items);

Correct Output

5
1,2,4,5
1,2,4,5
false

Why this output?

Explanation: filter never mutates — both removed and removedVal are new arrays. original items stays at length 5. Both approaches produce the same result.

Key Insight: filter is the idiomatic React way to delete from array state. It returns a new array and never mutates. removed === items is false, so React will detect the change.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz