Skip to content

Svelte’s reactivity with array operation

I’m studying svelte.

the tutorial states that responsiveness is based on assignment and consequently operations with array such as array.push() must have an assignment.

array.push() can be converted to numbers = [...numbers, numbers.length + 1] .

How to convert pop, shift, unshift, splice and other similar operation?


Unshift is the easiest, just use the reverse construction of the push

let arr = [1,2,3,4]
arr = [0, ...arr]

Shift can be rewritten using array destructuring, taking the first element and then spreading the rest back into the array-

let arr = [1,2,3,4];
[first, ...arr] = arr;

For pop and splice there is not really a shortcut you can follow, but you can always just reassign after doing the operation:

arr = arr