DEV Community

Robin Kretzschmar
Robin Kretzschmar

Posted on • Edited on

JS: use spread to exclude properties

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

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

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)

Collapse
 
mschinis profile image
Michael Schinis

Although the gist of the above is correct, the right hand side of the following code creates a copy of the firstObject before extracting age, and creating secondObject, allocating more memory unnecessarily.

const {age, ...secondObject} = {...firstObject};
Enter fullscreen mode Exit fullscreen mode

The following achieves the same outcome, but skips the extra allocation.

const {age, ...secondObject} = firstObject
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darksmile92 profile image
Robin Kretzschmar

Thank you for the explanation, you are absolutely correct about this. That was is more efficient 👍

Collapse
 
marcselman profile image
Marc Selman

You might wanna update your original post for people who don't read the comments. 😉

Thread Thread
 
darksmile92 profile image
Robin Kretzschmar

Good catch, thanks!
Lost track of it, updated :)

Collapse
 
essofyany profile image
essofyany

thanks bro <3

Collapse
 
erickgonzalez profile image
Erick

THANK YOU SO MUCH ;)

Collapse
 
jessehattabaugh profile image
Jesse Hattabaugh

It's a minor detail, but technically this isn't the "spread" operator, it's the "rest" operator when you use it in destructuring.