Array Destructuring
Array destructuring uses square brackets ([]) on the left side of the assignment to extract values based on their position (index) in the array.
Get Tarun Pandey’s stories in your inbox
Join Medium for free to get updates from this writer.
Basic Assignment: The order of variables matters.
const fruits = ["Bananas", "Oranges", "Apples"];
const [fruit1, fruit2, fruit3] = fruits;
console.log(fruit1); // "Bananas"Skipping Values: You can ignore elements by using commas to skip positions.
const fruits = ["Bananas", "Oranges", "Apples", "Mangos"];
const [fruit1, , fruit3] = fruits;
console.log(fruit1); // "Bananas"
console.log(fruit3); // "Apples"Rest Syntax: The rest syntax (...) collects the remaining elements into a new array, and must be the last element in the pattern.
const numbers = [10, 20, 30, 40, 50];
const [a, b, ...rest] = numbers;
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]Swapping Variables: Destructuring simplifies swapping two variables without a temporary variable.
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1Default Values: You can assign a default value if the extracted value is undefined.
const [name, favoriteFood = "Pizza"] = ["John"];
console.log(name); // "John"
console.log(favoriteFood); // "Pizza"




