Skip to content

Array reactive: $state([]) and JS [] behave differently Array.push() #15505

Open
@Fd929c2CE5fA

Description

@Fd929c2CE5fA

Describe the bug

In JS, Array.push() should preserve the original object reference.
But $state([]) does not seem to follow that logic.
This breaks the expected behavior of Svelte Array reactivity.

Reproduction

<script>
	let array = $state([[1,2]]);
	$inspect(array);
	let array2 = [[1,2]]; // JS Native Array for reference

	function click() {
		// order A
		const a = [3,4];
		array.push(a);
		array2.push(a);
		setTimeout(() => {
			a[1] = "AAA"; // "4" should change to "AAA"
			console.log(array2);
		}, 500);

		// order B
		array.push([5,6]);
		const b = array.at(-1);
		setTimeout(() => {
			b[1] = "BBB"; // "6" should change to "BBB"
		}, 500);
	}
	
</script>

<button onclick={click}>add</button>

{#each array as arr}
	<p>{arr[0]}/{arr[1]}</p>
{/each}

Playground

Logs

System Info

Svelte v5.20.4

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions