Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte value assignment does not update

Why doesn’t this value assignment work?

<script>
    let numbers = [1, 2, 3, 4];

    function addNumber() {
        numbers = numbers.push(numbers.length + 1);
    }

    $: sum = numbers.reduce((total, currentNumber) => total + currentNumber, 0);
</script>

<p>{numbers.join(' + ')} = {sum}</p>

<button on:click={addNumber}>
    Add a number
</button>

But when I change:

function addNumber() {
    numbers = numbers.push(numbers.length + 1);
}

to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function addNumber() {
    numbers.push(numbers.length + 1);
    numbers = numbers;
}

it works, even though it’s the same(?)

>Solution :

Array.prototype.push returns the new length of the array, so that is why it did not work as expected

you could also use concat or spread op instead

function addNumber() {
    numbers = numbers.concat([numbers.length + 1]);
}
function addNumber() {
    numbers = [...numbers, numbers.length + 1];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading