loading...

... explained as simply as I humanly can

phocks profile image Joshua Byrd ・1 min read

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 ]
Enter fullscreen mode Exit fullscreen mode

... 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 }
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

... 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 }
Enter fullscreen mode Exit fullscreen mode

That's it!

Discussion

pic
Editor guide
Collapse
kenbellows profile image
Ken Bellows

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

Collapse
phocks profile image
Joshua Byrd Author

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.

Collapse
kensixx profile image
Ken Flake

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!