Arrays
Explore arrays, how to create and manipulate them, access elements, and use array methods.
Array Destructuring
What is Array Destructuring?
Array destructuring is a powerful feature in JavaScript (ES6+) that allows you to unpack values from arrays (or properties from objects) into distinct variables. It provides a concise and readable way to extract multiple values from an array at once. It simplifies assigning array elements to individual variables.
Instead of accessing array elements using their index (e.g., myArray[0]
, myArray[1]
), destructuring lets you create variables that directly correspond to the desired elements.
Extracting Values from Arrays
Here's how to use array destructuring to extract values into individual variables:
// Example Array
const colors = ['red', 'green', 'blue'];
// Destructuring Assignment
const [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // Output: red
console.log(secondColor); // Output: green
console.log(thirdColor); // Output: blue
- Syntax: The left-hand side of the assignment uses square brackets
[]
to specify the variables to which you want to assign the array values. The order of the variables matters; it corresponds to the order of elements in the array. - Variable Names: You can choose any valid variable names for the extracted values.
- Default Values: You can provide default values in case the array doesn't have enough elements for all the variables:
const numbers = [1, 2]; const [a, b, c = 3] = numbers; console.log(a); // Output: 1 console.log(b); // Output: 2 console.log(c); // Output: 3 (default value)
- Skipping Elements: You can skip elements by leaving a space in the destructuring pattern:
const data = ['John', 'Doe', 30, 'Engineer']; const [firstName, , age] = data; // Skip the second element (Doe) console.log(firstName); // Output: John console.log(age); // Output: 30
- Rest Parameter: Use the rest parameter (
...
) to collect the remaining elements of an array into a new array:const fruits = ['apple', 'banana', 'orange', 'grape']; const [firstFruit, secondFruit, ...restOfFruits] = fruits; console.log(firstFruit); // Output: apple console.log(secondFruit); // Output: banana console.log(restOfFruits); // Output: ['orange', 'grape']
Practical Examples
Array destructuring is particularly useful in the following scenarios:
- Returning multiple values from a function.
- Swapping variable values easily.
- Working with API responses that return arrays of data.
Example: Returning multiple values from a function
function getCoordinates() {
return [10, 20]; // Latitude, Longitude
}
const [latitude, longitude] = getCoordinates();
console.log("Latitude:", latitude); // Output: Latitude: 10
console.log("Longitude:", longitude); // Output: Longitude: 20
Example: Swapping Variables
let a = 1;
let b = 2;
[a, b] = [b, a]; // Swap the values of a and b
console.log("a:", a); // Output: a: 2
console.log("b:", b); // Output: b: 1