const myArray = [1, 2, 3, 4, 5]; // Destructuring assignment const [first, second, , fourth] = myArray; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(fourth); // Output: 4
In the above example, we have an array
myArray with five elements. By using destructuring assignment, we declare variables
fourth and assign them the corresponding values from the array. The third element of the array is skipped using an empty slot in the destructuring assignment.
Array destructuring also supports default values. If an element in the array is
undefined or absent, the default value will be used. Here's an example:
const myArray = [1, 2]; const [first = 0, second = 0, third = 0] = myArray; console.log(first); // Output: 1 console.log(second); // Output: 2 console.log(third); // Output: 0 (default value)
In the example above, the array
myArray has only two elements. By providing default values (
0 in this case) for the variables
third, even if the corresponding elements are absent, the destructuring assignment will assign the default values.
You can also use the rest parameter syntax (
...) to capture the remaining elements of an array. Here's an example:
const myArray = [1, 2, 3, 4, 5]; const [first, ...rest] = myArray; console.log(first); // Output: 1 console.log(rest); // Output: [2, 3, 4, 5]
In the example above, the variable
first captures the first element of the array, and the
rest variable uses the rest parameter syntax (
...) to capture the remaining elements as an array.
Array destructuring can be particularly useful when working with functions that return arrays or when extracting values from complex data structures like objects containing arrays.
Remember that array destructuring relies on the position of elements within the array. If you only need to access specific properties of an object, you should use object destructuring instead.