DEV Community 👩‍💻👨‍💻

Discussion on: Destructuring Assignment in ES6- Arrays

karfau profile image
Christian Bewernitz • Edited on

Tank you for posting, didn't know about this way of skipping elements.

But the following sentence might be misleading (if it wouldn't be for the headline above):

What if we want to get the first and last item on the array...?

The way you show is really only working if you know the size of the array, which obviously you don't always do, e.g. when destructing an argument inside a function.

If you don't know it, you could do the following without touching the initial array:

const input = ["Hello", "I" , "am", "Sarah"];
const [greeting,] = input;
//rest == ["I" , "am", "Sarah"]
const name = rest.pop(); // rest is modified but input isn't
//or if you prefer or need more then one from the end
const [last, secondLast] = rest.reverse(); // rest is modified!
Enter fullscreen mode Exit fullscreen mode

The must always be the last part, so const [greeting, ...dontCare, name] = ... does not work.

We should also mention how destructing works when encountering [] and undefined:

var [a, b,] = [];
console.log(a,b,rest);//undefined, undefined, []

var [ouch] = undefined;//Uncaught TypeError: undefined is not iterable
Enter fullscreen mode Exit fullscreen mode

Hm, iterable? What happens if we destruct some other iterable?

var [a, b,] = "abc,d";
console.log(a, b, rest);//"a", "b", ["c", ",", "d"]
Enter fullscreen mode Exit fullscreen mode

Happy coding!

viricruz profile image

Thank you for explaining this in an understandable human way!. It was very easy to digest and helpful.

ramachintaguntla profile image

I dint know that even string could be destructed.. i was under the impression that only Array and Objects can be done.. are there any others that can be destructed?(other than strings, objects, arrays)

sayopaul profile image
Sayo Paul

Wow . Thank you so much for this