HardState & Immutability💻 Output Question

structuredClone vs spread for deep state copy

💡

Hint

Spread is shallow. For nested arrays inside nested objects, you must spread at every level. structuredClone() or JSON parse/stringify for deep copies — though both have limitations.

What does this output?

const state = {
  user: { name: 'Alice', tags: ['admin', 'user'] }
};

// Shallow spread — nested array still shared
const shallow = { ...state, user: { ...state.user } };
shallow.user.tags.push('guest'); // mutates original!

// Deep clone — fully independent
const deep = JSON.parse(JSON.stringify(state));
deep.user.tags.push('moderator'); // does NOT mutate

console.log(state.user.tags.length);
console.log(shallow.user.tags.length);
console.log(deep.user.tags.length);
console.log(state.user.tags === shallow.user.tags);

Correct Output

3
3
3
true

Why this output?

Explanation: After push to shallow.user.tags: original.tags has 3. shallow shares the tags array reference. deep.user.tags is fully independent — also starts at 2 items then gets 'moderator' = 3.

Key Insight: Spread is shallow. For nested arrays inside nested objects, you must spread at every level. structuredClone() or JSON parse/stringify for deep copies — though both have limitations.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz