Destructuring Array Parameters
What you'll learn: How to use array destructuring directly in function parameter lists to automatically extract elements from array arguments.
The Core Idea
Just like you can destructure objects in function parameters (the previous lesson), you can also destructure arrays. When a function expects an array argument, you can extract specific elements right in the parameter list instead of accessing them by index inside the function body.
This is especially useful when you know the structure of the array being passed and only care about certain positions.
Basic Syntax
Instead of writing:
function processCoordinates(coords) {
const x = coords[0];
const y = coords[1];
console.log(`X: ${x}, Y: ${y}`);
}
processCoordinates([10, 20]);
You can destructure in the parameter list:
function processCoordinates([x, y]) {
console.log(`X: ${x}, Y: ${y}`);
}
processCoordinates([10, 20]);
// Output: X: 10, Y: 20
Combining with Defaults and Rest
You can use all the destructuring features you've learned:
function greet([first, last = 'Doe', ...titles]) {
console.log(`Hello ${first} ${last}`);
console.log('Titles:', titles);
}
greet(['Jane', 'Smith', 'Dr.', 'PhD']);
// Hello Jane Smith
// Titles: ['Dr.', 'PhD']
greet(['John']);
// Hello John Doe
// Titles: []
When to Use This
Array parameter destructuring shines when working with coordinate pairs, RGB color arrays, or any function that consistently receives arrays with known structures.
Key Takeaway: Array destructuring in parameters lets you extract array elements directly in the function signature, making your code cleaner and your intentions clearer without manual indexing.