DEV Community

Joshua Byrd
Joshua Byrd

Posted on • Edited on

19 10

... (rest and spread) explained as simply as I humanly can

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!

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (3)

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 • Edited

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!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay