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!
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
Hm, iterable? What happens if we destruct some other iterable?
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)
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):
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:
The
...name
must always be the last part, soconst [greeting, ...dontCare, name] = ...
does not work.We should also mention how destructing works when encountering
[]
andundefined
:Hm, iterable? What happens if we destruct some other iterable?
Happy coding!
Thank you for explaining this in an understandable human way!. It was very easy to digest and helpful.
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)
Wow . Thank you so much for this