Destructuring with skipped elements
Array destructuring with skipped elements is a very useful technique for when you need to extract only some values and skip the rest.
Basic example:
javascript
const arr = [10, 20, 30, 40];
const [first, , third] = arr;
console.log(first); // 10
console.log(third); // 30- Between the commas there is an empty spot (
,) - this is skipping an element. - In this case we skip the second element (
20).
Pattern:
javascript
const [a, , c, , e] = [1, 2, 3, 4, 5];
console.log(a, c, e); // 1 3 5Each comma marks a position in the array. If you want to skip a value - just leave an empty spot between commas.
You can also use rest (...) together:
javascript
const [first, , ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest); // [3, 4, 5]- We skipped the second element (
2), - The rest were collected into a new array via
...rest.
Skipping several in a row:
javascript
const arr = [100, 200, 300, 400, 500];
const [first, , , fourth] = arr;
console.log(first); // 100
console.log(fourth); // 400With destructuring inside a nested array:
javascript
const matrix = [
[1, 2],
[3, 4],
[5, 6]
];
const [, , [x, y]] = matrix;
console.log(x, y); // 5 6We skipped the first two rows and grabbed the last one directly.
In short:
| Task | How to do it |
|---|---|
| Skip an element | add an extra comma |
| Skip several | several commas in a row |
| Take the rest | use ...rest |
| Works with | arrays, function results, etc. |
Example with a function:
javascript
function getCoords() {
return [10, 20, 30];
}
const [x, , z] = getCoords();
console.log(x, z); // 10 30Summary: To skip elements during destructuring, just leave an empty spot between commas:
javascriptconst [a, , c] = [1, 2, 3]; // second element skippedYou can also combine this with
...restfor even more flexibility.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.