Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign full array to destructuring variable

In Clojure destructuring it’s possible to also have a binding for the full array using :as, is something similar possible in Javascript?

For example,

const queue = [[1, 2]];
const [x, y :as pos] = queue.shift();

where x would be 1, y would be 2 and pos would be [1, 2]?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

or is an extra in-between step necessary, like

const queue = [[1, 2]];
const pos = queue.shift();
const [x, y] = pos;

>Solution :

You can’t get the parent and nested properties at the same time during destructuring.

I’d do it separately for readability. You could destructure the queue array first and then destructure the pos array. This avoids the mutation of the queue array

const queue = [ [1, 2] ],
      pos = queue.shift(),
      [x, y] = pos;

console.log(x, y)
console.log(pos)

BUT, it is possible to do it in single line. If you destructure the array like an object. Get the 0 property to a variable and destructure the nested array

const queue = [ [1, 2] ];

const { 0: pos, 0: [x, y] } = queue

console.log(x, y)
console.log(pos)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading