Spread for Function Arguments In JavaScript
Using the ... operator (spread operator) allows you to define functions with normal named parameters, but call those functions with arrays. Which allows the sets of data going into functions to be mapped easier. Firstly, this was possibly before, but only with the awkward apply syntax:
function boxVolume(width, height, length) { return width * height * length; } const params = [5, 4, 3]; console.log(boxVolume.apply(undefined, params)); // 60
The undefined sets the value of the called functions this. Here is the equivalent with spread:
const params = [5, 4, 3]; console.log(boxVolume(...params)); // 60
This is useful when calling boxVolume with lots of dynamic data. For example, the below calculates all length 3 volume combinations:
for (let width = 1; width < 4; width += 1) { for (let height = 1; height < 4; height += 1) { for (let length = 1; length < 4; length += 1) { const dimensions = [width, height, length]; console.log(dimensions, boxVolume(...dimensions)); } } } // [ 1, 1, 1 ] 1 // [ 1, 1, 2 ] 2 // ... Alot more results // [ 3, 3, 3 ] 27
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/spreadArgs.js













