Array Destructuring

Array Destructuring
πŸ‘¨β€πŸ’Ό Array destructuring extracts elements by position. It's especially useful for working with 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
🐨 Open
index.ts
and:
  1. From scores ([95, 92, 88, 87, 76]), destructure highest and secondHighest (expected 95 and 92)
  2. Destructure winner and others with the rest pattern (expected 95 and [92, 88, 87, 76])
  3. Destructure coordinates into x, y, and z (expected 10, 20, 30)
  4. Create getMinMax(nums) that returns a [min, max] tuple for the input array, then destructure const [min, max] = getMinMax(scores) (for scores, expected 76 and 95)
  5. Export highest, secondHighest, winner, others, x, y, z, min, max, and getMinMax

Please set the playground first

Loading "Array Destructuring"
Loading "Array Destructuring"