Immutable patterns help keep your data safe by not changing the original values. This makes your app easier to understand and bugs easier to find.
Immutable patterns for updates in Svelte
// Updating an array immutably let newArray = [...oldArray, newItem]; // Updating an object immutably let newObject = {...oldObject, key: newValue};
Use the spread operator ... to copy arrays or objects.
Always assign the new value to trigger Svelte's reactivity.
let numbers = [1, 2, 3]; numbers = [...numbers, 4];
let user = { name: 'Anna', age: 25 }; user = { ...user, age: 26 };
let todos = [{ id: 1, done: false }]; todos = todos.map(todo => todo.id === 1 ? { ...todo, done: true } : todo);
This Svelte component shows a list of fruits. When you click buttons, it updates the list immutably by creating new arrays. This triggers Svelte to update the displayed list.
<script> let items = ['apple', 'banana']; function addItem(newItem) { // Use immutable update to add new item items = [...items, newItem]; } function updateFirstItem(newName) { // Update first item immutably items = items.map((item, index) => index === 0 ? newName : item); } </script> <h2>Fruits:</h2> <ul> {#each items as item} <li>{item}</li> {/each} </ul> <button on:click={() => addItem('orange')}>Add Orange</button> <button on:click={() => updateFirstItem('grape')}>Change First to Grape</button>
Directly changing arrays or objects (like items.push()) won't trigger Svelte updates.
Immutable updates help Svelte detect changes and update the UI efficiently.
Use immutable patterns especially when working with stores or passing props.
Immutable updates create new arrays or objects instead of changing originals.
This helps Svelte know when to update the screen.
Use the spread operator and array methods like map for easy immutable updates.
Practice
Solution
Step 1: Understand Svelte's reactivity system
Svelte tracks changes by comparing references of variables. If the reference changes, it knows to update the UI.Step 2: Why immutable updates help
Creating new arrays or objects changes the reference, so Svelte detects the change and updates the screen correctly.Final Answer:
Because creating new arrays or objects helps Svelte detect changes and update the UI. -> Option DQuick Check:
Immutable updates = UI updates detected [OK]
- Thinking mutable updates automatically update UI
- Believing Svelte forbids mutable updates
- Confusing immutability with data never changing
4 to numbers?Solution
Step 1: Check each option for immutability
numbers.push(4); uses push which mutates the original array. numbers[3] = 4; directly assigns an index, mutating the array. numbers.concat(4); calls concat but does not assign the result back, so no update happens.Step 2: Identify the correct immutable update
numbers = [...numbers, 4]; uses the spread operator to create a new array with the old items plus 4, then assigns it back to numbers, which is the correct immutable pattern.Final Answer:
numbers = [...numbers, 4]; -> Option BQuick Check:
Spread operator creates new array [OK]
- Using push which mutates original array
- Not assigning result of concat back
- Directly modifying array indexes
let todos = [
{ id: 1, text: 'Buy milk', done: false },
{ id: 2, text: 'Walk dog', done: false }
];
// Update to mark todo with id 2 as done
todos = todos.map(todo => todo.id === 2 ? { ...todo, done: true } : todo);What will be the value of
todos after this update?Solution
Step 1: Understand the map update logic
The map goes through each todo. If the todo's id is 2, it creates a new object with done set to true. Otherwise, it returns the original todo unchanged.Step 2: Apply the update to each todo
Todo with id 1 remains unchanged with done: false. Todo with id 2 is updated to done: true.Final Answer:
[{ id: 1, text: 'Buy milk', done: false }, { id: 2, text: 'Walk dog', done: true }] -> Option AQuick Check:
Only todo with id 2 is marked done [OK]
- Updating wrong todo item
- Mutating original todo instead of creating new
- Not returning updated todo in map
let user = { name: 'Alice', age: 25 };
// Update age
user.age = 26;
user = user;Solution
Step 1: Identify mutation in the code
The line user.age = 26 directly changes the existing object, which is a mutation.Step 2: Understand Svelte's change detection
Assigning user = user does not change the reference, so Svelte does not detect any change and will not update the UI.Final Answer:
Directly modifying user.age mutates the original object, so Svelte may not detect the change. -> Option CQuick Check:
Mutating object without new reference breaks reactivity [OK]
- Mutating object properties directly
- Assigning same object reference back
- Expecting UI to update without new object
let profile = {
name: 'Bob',
address: { city: 'NY', zip: '10001' }
};
// You want to update zip to '10002' immutably. Which is correct?Solution
Step 1: Understand nested immutable update
To update a nested property immutably, create new copies of each level: first the nested object, then the outer object.Step 2: Analyze each option
profile.address.zip = '10002'; profile = profile; mutates nested property directly, no new reference. profile = { ...profile, zip: '10002' }; updates zip at top level, ignoring nesting. profile.address = { zip: '10002' }; profile = profile; replaces address with incomplete object, losing city. profile = { ...profile, address: { ...profile.address, zip: '10002' } }; correctly creates new address object with updated zip, then new profile object.Final Answer:
profile = { ...profile, address: { ...profile.address, zip: '10002' } }; -> Option AQuick Check:
Nested spread creates new objects immutably [OK]
- Mutating nested properties directly
- Not copying nested objects fully
- Losing other nested properties by overwriting
Ready to prove it?
Pass the test and this pattern moves unknown
