Object rest spread rather than Object.assign

Creating new objects just got a whole lot neater.

Gav McKenzie
Author
Gav McKenzie
Published
Aug 28, 2018
Topics
Industry

So you already try to create new objects rather than mutating current ones because you like your JavaScript to be functional.

const foo = { id: 1, name: 'Etch' };
const bar = Object.assign({}, foo);
// bar = { id: 1, name: 'Etch' };

Well the object rest spread syntax lets you do this in a little bit of a nicer way.

const bar = { ...foo };

This one is still in the proposal stages so you’ll need to use babel or something similar to make it work.

Arrays

Hey this rest spread thing also works with arrays!

const foo = [1, 2, 3, 4];
const bar = [ ...foo ];
// bar = [1, 2, 3, 4];

You can use this where you would have used Array.push or Array.concat

const foo = [1, 2];
const bar = [3, 4];
const baz = [...foo, ...bar];
// baz = [1, 2, 3, 4];

Merging objects

You can add or overwrite elements in the object just like you would with Object.assign.

const foo = { id: 1, name: 'Etch' };
const bar = {
...foo,
name: 'Etch Software',
services: 'Software development',
};
// bar = {
// id: 1,
// name: 'Etch Software',
// services: 'Software development',
// };

Object destructuring

You can combine the rest spread operator with object destructuring to pluck variables you want out of an object and do something with the rest of them.

// A button component that accepts children
// and passes the rest of the props through.
function UselessButton({ children, ...rest }) {
return (
<button {...rest}>
{children}
</button>
);
}

Further reading at Google Developers.