loading...

Discussion on: Destructuring Assignment in ES6- Arrays

Collapse
karfau profile image
Christian Bewernitz

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, ...rest] = 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 ...name 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, ...rest] = [];
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, ...rest] = "abc,d";
console.log(a, b, rest);//"a", "b", ["c", ",", "d"]
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Collapse
ramachintaguntla profile image
ramachintaguntla

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)

Collapse
viricruz profile image
ViriCruz

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

Collapse
sayopaul profile image
Sayo Paul

Wow . Thank you so much for this