... (rest and spread) explained as simply as I humanly can
Joshua Byrd
Posted on March 21, 2019
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!
๐ ๐ช ๐
๐ฉ
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.