Three dots ...
does two different things depending on how you use them.
Spread:
...
in front of an array removes the outside []
.
const x = [1, 2, 3];
const y = [0, ...x, 4, 5, 6];
console.log(y); // [ 0, 1, 2, 3, 4, 5, 6 ]
...
in front of an object removes the outside {}
.
const x = { one: 1, two: 2, three: 3 };
const y = { ...x, four: 4, five: 5, six: 6 };
console.log(y); // { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6 }
Rest:
...
when destructuring an array, assigns the rest of the elements.
const x = [1, 2, 3];
const [one, ...rest] = x
console.log(one); // 1
console.log(rest); // [2, 3]
...
when destructuring an object, assigns the rest of the properties.
const x = { one: 1, two: 2, three: 3 };
const { one, ...rest } = x;
console.log(one); // 1
console.log(rest); // { two: 2, three: 3 }
That's it!
Top comments (3)
Nice one, I think "removes the
[]
/{}
" is the #1 best way to explain the spread operation. Anything else requires way too many words, and doesn't get the point across as clearly anyway, especially for a beginner.Also, add the #explainlikeimfive tag! This is perfect for it
Thanks! Yeah it took me ages of reading, and re-reading complicatedly worded explanations before I came up with this way of explaining it. Works well! Tag added too.
Thanks for this, Joshua. I've been wondering what this means. It was not really hard to understand, well, the way you put it out. Thank you very much!