Array destructuring unpacks any iterable by position: const [a, b] = list. Skip slots with commas, set defaults (applied only for undefined, not null) and nest patterns; objects destructure by name instead (Object Destructuring).
const [a, , b = 3, c] = [7, 8]; // skip a slot, default, missing
const [[x, y], [z]] = [[1, 2], 'hi']; // nested; any iterable works
console.log(a, b, c, x, y, z);
function* naturals() { let n = 0; while (true) yield n++; }
const [first, second] = naturals(); // pulls only two values
console.log(first, second);
function shuffle(arr) { // Fisher-Yates: unbiased, in place
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]]; // swap without a temp variable
}
return arr;
}
console.log(shuffle(['A', 'K', 'Q', 'J']).toSorted().join(''));7 3 undefined 1 2 h 0 1 AJKQ
Typical uses are pairs returned from functions (React 7,897 's const [count, setCount] = useState(0)) and for (const [key, value] of map). Put a ; before a line that starts with [, or it is parsed as an index.