**Destructuring** unpacks array values into distinct variables using pattern matching. It's particularly powerful for: swapping variables, function return values, ignoring elements (using `,`), and collecting the rest (`...rest`).
1Understanding Array Destructuring
Destructuring unpacks array values into distinct variables using pattern matching. It's particularly powerful for: swapping variables, function return values, ignoring elements (using ,), and collecting the rest (...rest).
Swap variables elegantly with destructuring: [a, b] = [b, a] — no temporary variable needed.
// Basic destructuring
const [name, age, city] = ['Alice', 30, 'NYC'];
console.log(name, age, city); // Alice 30 NYC
// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
// Skip elements
const [,, third] = [10, 20, 30];
console.log(third); // 302Practical Example
Here is a real-world application of Array Destructuring showing how it is used in production JavaScript code.
// Rest + defaults
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// Destructure function return
function minMax(arr) {
return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = minMax([3, 1, 7, 2, 9]);
console.log(min, max); // 1 93Best Practices
Follow these guidelines when working with Array Destructuring:
1. Use rest (...rest) to collect remaining elements
2. Provide default values for potentially undefined elements
3. Use destructuring in function parameters for clarity
Tip: Swap variables elegantly with destructuring: [a, b] = [b, a] — no temporary variable needed.
// Basic destructuring
const [name, age, city] = ['Alice', 30, 'NYC'];
console.log(name, age, city); // Alice 30 NYC
// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
// Skip elements
const [,, third] = [10, 20, 30];
console.log(third); // 30