JavaScript provides a very handy possibility to destructure any array and give custom names to the variables in it.

Let’s assume we start with a simple array of numbers:

const numbers = [1, 2, 3, 4, 5];

To get the first 2 elements from this array, we can use the destructuring assignment. All you need is square brackets and the names for your variables:

const [first, second] = numbers;

console.log(first);        // 1
console.loog(second);      // 2

And if you need a reference for remaining elements, you can place them into a separate array with the spread operator.

const [first, second, ...rest] = numbers;

console.log(rest);         // [ 3, 4, 5 ]

Keep in mind that the destructuring assignment doesn’t modify the original array in any way.

Read more JavaScript tutorials or Learn Full-Stack JS from scratch!