Confused as to why this works

I came across this code in the blog, but don’t the variables “nextToLast” and “last” need to be declared or defined first?

const fibonacci = (num = 2, array = [0, 1]) => {
    while (num > 2) {
        const [nextToLast, last] = array.slice(-2);
        array.push(nextToLast + last);
        num -= 1;
    }
    return array;
}

console.log(fibonacci(10));

This line const [nextToLast, last] = array.slice(-2); uses array destructuring and is a way of declaring, and assigning multiple elements at once.

An equal piece of code using the same values as the example would be:

const nextToLast = array[array.length - 2];
const last = array[array.length - 1];

So we are declaring individual variables with that line and not necessarily a new array with the square brackets correct?

That is correct. The “array” on the left is just a list of the individual variable names, the array on the right is a real array and the variables will be assigned to the values based on what index they share.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.