Array Destructuring


Array destructuring is a powerful ES6 feature that allows you to unpack values from arrays or properties from objects into distinct variables. This syntax makes your code more concise and readable, especially when dealing with functions that return arrays or when you need to swap variable values.


Example 1: Basic Array Destructuring

// Define an array of user data
const user = ['Jane', 'Doe', 'Admin'];

// Extract the first two values into variables
const [firstName, lastName] = user;

console.log(firstName); // Output: Jane
console.log(lastName);  // Output: Doe

Explanation This example demonstrates the fundamental use of array destructuring. We are extracting the first two elements from the user array and assigning them to new variables, firstName and lastName, in a single, clean line of code.


Example 2: Skipping Elements

// Define an array of numbers
const numbers = [10, 20, 30, 40, 50];

// Extract the first, third, and fifth elements
const [first, , third, , fifth] = numbers;

console.log(first); // Output: 10
console.log(third); // Output: 30
console.log(fifth); // Output: 50

Explanation By using a comma , as a placeholder, you can skip over elements in the array that you don't need. In this case, we ignored the second and fourth elements (20 and 40) to only assign the desired values to our variables.


Example 3: Using the Rest Parameter

// Define an array with multiple values
const rankings = ['Gold', 'Silver', 'Bronze', 'Participant', 'Honorable Mention'];

// Extract the top rank and collect the rest into a new array
const [winner, ...others] = rankings;

console.log(winner); // Output: Gold
console.log(others); // Output: ['Silver', 'Bronze', 'Participant', 'Honorable Mention']

Explanation The rest parameter ... gathers all remaining elements of an array into a new array. This is incredibly useful for separating a primary element from a list of other, less critical elements.


Example 4: Swapping Variables

// Initialize two variables
let a = 100;
let b = 200;

// Swap the values of a and b in one line
[a, b] = [b, a];

console.log(a); // Output: 200
console.log(b); // Output: 100

Explanation Array destructuring provides an elegant way to swap the values of two variables without needing a temporary third variable. The right side creates a temporary array [200, 100], and the left side immediately destructures it back into a and b in the new order.


Example 5: Assigning Default Values

// Define an array with fewer elements than variables
const settings = ['dark'];

// Destructure the array, providing a default value for theme
const [theme = 'light', fontSize = 16] = settings;

console.log(theme);    // Output: dark
console.log(fontSize); // Output: 16

Explanation You can provide default values for variables in case an array element is undefined. Since the settings array only has one element, theme is assigned 'dark', but fontSize falls back to its default value of 16.


Example 6: Destructuring Function Return Values

// A function that returns an array with latitude and longitude
function getCoordinates() {
  return [47.0379, -122.9007];
}

// Destructure the returned array directly into variables
const [latitude, longitude] = getCoordinates();

console.log(latitude);  // Output: 47.0379
console.log(longitude); // Output: -122.9007

Explanation This pattern is very common for cleanly handling functions that return multiple values as an array. We call the getCoordinates function and immediately destructure its array return value into the latitude and longitude variables.


Example 7: Nested Array Destructuring

// Define a nested array representing a user and their location
const userProfile = ['John Doe', 30, ['New York', 'NY']];

// Destructure the nested array to get the city
const [name, , [city, state]] = userProfile;

console.log(name);  // Output: John Doe
console.log(city);  // Output: New York
console.log(state); // Output: NY

Explanation Destructuring can also be applied to nested arrays. Here, we extract the name, skip the age, and then apply another level of destructuring to the inner array to extract the city and state.