Ignoring Elements During Array Destructuring

Sometimes when destructuring an array you do not want to keep all of the elements. JavaScript destructuring allows us to ignore specific elements. This is done by not declaring a variable to store the element at the index you wish to ignore.

const [a, , b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 3

This is especially useful for destructuring the results of a call to String.match() for example. The result will contain an array with the entire matched string and any captured groups. If the matching string is not required it can be ignored during destructuring.

console.log('some-file.js:14:3'.match(/(.*):(\d+):(\d+)/)); // ["some-file.js:14:3", "some-file.js", "14", "3"]

const [, file, line, column] = 'some-file.js:14:3'.match(/(.*):(\d+):(\d+)/);
console.log(file); // "some-file.js"
console.log(line); // "14"
console.log(column); // "3"
JavaScript
SCROLL TO TOP