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;
console.log(first); // Output: 10
console.log(second); // Output: 20
console.log(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"
console.log(fruit1); // Output: Apple
console.log(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;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(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;
console.log(color1); // Output: Red
console.log(color2); // Output: Green
console.log(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];
console.log(x); // Output: 10
console.log(y); // Output: 5