I thought I'd share this small trick with you because I find myself looking this up every now and then when I need it.
The spread operator in JavaScript can be very useful.
For example to create a copy of an object:
const firstObject = {id: 0, name: 'John'};
const secondObject = {...firstObject};
console.log(firstObject);
console.log(secondObject);
// { id: 0, name: 'John'}
// { id: 0, name: 'John'}
But did you know you can also use it to except properties when spreading?
const firstObject = {id: 0, firstName: 'John', lastName: 'Smith', age: 77 };
// take every property except age:
const {age, ...secondObject} = firstObject;
console.log(firstObject);
console.log(secondObject);
// { id: 0, firstName: 'John', lastName: 'Smith', age: 77 }
// { id: 0, firstName: 'John', lastName: 'Smith' }
The above example will extract age
as own variable and will put the remaining in the object secondObject
. You can do that with as many properties as you want.
Top comments (7)
Although the gist of the above is correct, the right hand side of the following code creates a copy of the
firstObject
before extractingage
, and creatingsecondObject
, allocating more memory unnecessarily.The following achieves the same outcome, but skips the extra allocation.
Thank you for the explanation, you are absolutely correct about this. That was is more efficient 👍
You might wanna update your original post for people who don't read the comments. 😉
Good catch, thanks!
Lost track of it, updated :)
thanks bro <3
THANK YOU SO MUCH ;)
It's a minor detail, but technically this isn't the "spread" operator, it's the "rest" operator when you use it in destructuring.