Spread Syntax in JavaScript
Spread parameters allow arrays other iterables to be used directly where arguments are needed, usually for function calls. Iterables in the case are mainly ones that can be used with for of: http://exploringjs.com/es6/ch_iteration.html#sec_iterable-data-sources. Firstly, this can be used to simplify apply syntax:
function greet(firstName, middleI, lastName) { console.log('Hello, ' + firstName + ' ' + middleI + ' ' + lastName); } // The names came in array format from an external source const names = ['Henry', 'S', 'Fop-doodle']; greet.apply(null, names); // Hello, Henry S Fop-doodle greet(...names); // Hello, Henry S Fop-doodle
It can also be used with array syntax for more complex operations like taking a part of the rest parameters:
greet(...names.slice(0, 2), 'Johnson'); // Hello, Henry S Johnson
Finally this spread syntax can be used for more general array operations:
const extendedName = ['Dr.', ...names, 'Senior']; // Each argument passed to console.log is separated with a space // Making it easy to do array print outs console.log(...extendedName);
Most rest operations can be simulated with more steps, but there is one that cannot. apply cannot be used to send in arrays to constructors. Which means array date definitions via new can only be done with spread:
const dateAsArray = [1990, 0, 19]; console.log(new Date(dateAsArray)); // Invalid Date // This will cause an error // console.log(new Date.apply(null, dateAsArray)); console.log(new Date(...dateAsArray)); // 1990-01-19T05:00:00.000Z (Exact display will vary by JS platform)
The spread syntax works on most platforms, just not IE 11 or Safari on mobile.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/spread.js














