0

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:

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

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

1 Answer 1

2

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];
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.