Destructuring

Just as you can destructure properties out of an object, you can destructure sequential elements out of an array into distinct, standalone variables.

Basic Destructuring

Instead of manually creating variables via index (const x = nums[0]), you can extract them cleanly in a single line using bracket [] syntax on the left side of the assignment.

const nums = [2, 4, 6];

// The variables are assigned in order
const [x, y, z] = nums;

console.log(x, y, z);
// Output: 2 4 6

If you only care about the first element, you can destructure just that one and ignore the rest:

const [firstElement] = nums;
console.log(firstElement); // Output: 2

Dealing with Undefined

If you attempt to destructure more variables than there are elements in the array, the extra variables are safely initialized as undefined.

const [x, y, z, a] = nums;
console.log(a); // Output: undefined

The Rest Operator

If you want to pull out specific items but bundle all the remaining elements into a single new array, you can use the rest operator (...) at the end of your destructuring pattern.

const nums = [2, 4, 6, 8, 10];

// Extract the first item, bundle the rest
const [first, ...theRest] = nums;

console.log(first);   // Output: 2
console.log(theRest); // Output: [4, 6, 8, 10]

If there are no elements left to capture, the rest operator results in an empty array [] (not undefined).