JavaScript Spread Properties
Usually, I don't blog about very new features that will (probably) be coming to JavaScript. But this feature has the potential to add a lot to JavaScript. Firstly, ES6 has a spread operator, but only for arrays and function calls. This is for object properties. It inserts all of an objects non-inherited properties in an object literal:
const objectA = { name: 'A' }; const objectB = { ...objectA }; console.log(objectB); // { name: 'A' } const objectC = { ...objectA, property1: 'value1' }; console.log(objectC); // { name: 'A', property1: 'value1' }
One of the simplist uses is to clean up the Object.assign syntax when you don't want to modify the original object. Object.assign allows you to copy one set of an object non-inherited properties to another:
const defaultPermissions = { name: 'A Person', isAdmin: false, canCreate: false, canDelete: false, }; const nonAdminUser = Object.assign({}, defaultPermissions, { canCreate: true, canDelete: true }); console.log(nonAdminUser); // { name: 'A Person', // isAdmin: false, // canCreate: true, // canDelete: true }
The problem is that forgetting to include {} will result in accidentally modifying the original object causing nasty consequences later (and its hard to notice). Instead spread properties can be used:
const nonAdminUser = { ...defaultPermissions, canCreate: true, canDelete: true }; console.info(nonAdminUser); // { name: 'A Person', // isAdmin: false, // canCreate: true, // canDelete: true }
Two objects can be directly merged if the overriding properties also come from a previous object too:
const nonAdminPermissions = { canCreate: true, canDelete: true }; const nonAdminUser3 = { ...defaultPermissions, ...nonAdminPermissions };
This feature already works in Node 8+ which is a stable long term support version. And is already a stage 3 feature which makes it likely that it will be accepted, so it is very likely to become a language feature. It just may take along time to see it in most browsers and other JS environments.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/restProperties.js
















