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

phocks

Joshua Byrd

Posted on March 21, 2019

... (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!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
phocks
Joshua Byrd

Posted on March 21, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About