Array Destructuring
π¨βπΌ Array destructuring extracts elements by position. It's especially useful for
working with tuples, function return values, and APIs that return arrays.
const colors = ['red', 'green', 'blue']
const [first, second, third] = colors
// first = 'red', second = 'green', third = 'blue'
Skipping Elements
Use empty slots to skip elements you don't need:
const [, , third] = colors // third = 'blue'
Rest Pattern
Collect remaining elements into a new array:
const [head, ...rest] = [1, 2, 3, 4, 5]
// head = 1, rest = [2, 3, 4, 5]
The spread/rest syntax was covered in Exercise 3. The
...rest pattern here
collects remaining array elements into a new array.Swapping Variables
Destructuring enables elegant swaps:
let a = 1
let b = 2
;[a, b] = [b, a] // a = 2, b = 1
- Destructure the first and second elements from an array
- Use the rest pattern to separate the first item from the rest
- Create a function that returns multiple values and destructure the result
π° Rest pattern with types:
const [first, ...rest]: [number, ...Array<number>] = numbers