How Array Destructuring Works:
Basic Assignment: Values are assigned to variables based on their position in the
array.
JavaScript
const numbers = [10, 20, 30];
const [first, second, third] = numbers;
[Link](first); // Output: 10
[Link](second); // Output: 20
[Link](third); // Output: 30
Skipping Values: Commas can be used to skip elements in the array.
JavaScript
const fruits = ["Apple", "Banana", "Cherry", "Date"];
const [fruit1, , fruit3] = fruits; // Skips "Banana"
[Link](fruit1); // Output: Apple
[Link](fruit3); // Output: Cherry
Rest Parameter: The rest parameter (...) can be used to capture remaining elements
into a new array.
JavaScript
const data = [1, 2, 3, 4, 5];
const [a, b, ...restOfData] = data;
[Link](a); // Output: 1
[Link](b); // Output: 2
[Link](restOfData); // Output: [3, 4, 5]
Default Values: Default values can be provided for variables in case the
corresponding array element is undefined.
JavaScript
const colors = ["Red", "Green"];
const [color1, color2, color3 = "Blue"] = colors;
[Link](color1); // Output: Red
[Link](color2); // Output: Green
[Link](color3); // Output: Blue
Swapping Variables: Destructuring provides a clean way to swap variable values
without a temporary variable.
JavaScript
let x = 5;
let y = 10;
[x, y] = [y, x];
[Link](x); // Output: 10
[Link](y); // Output: 5