Function Spread

We're back! Yesterday we looked at Array Spread, which is a handy way to combine arrays. Today we're looking at function spread, which is a way of distributing array items into a function as its arguments. To recap, here's the definition of the spread syntax:

The Spread operator takes an ellipses symbol ... and combines it with what Brandon Morelli terms a receiver in this Medium post. The receiver can be an array, a function, or an object.

The syntax for Function Spread is:

const iterableItem = ['some', 'kind', 'of', 'array'];
function someFunction(...iterableItem){
  // work goes here
};

In this case, the receiver is the function, which takes the spread notation as an argument.

At its most basic application, Function Spread is a way to pass an array with an unknown quantity of arguments to a function:

const blogNameArray = ["Code", "and", "Tacos"];
console.log(...blogNameArray);
// expected output: ["Code and Tacos"]

Function Spread also gives us an easy way to use built-in math functions without having to hard code values. For example, here's a basic Math.max() function:

console.log(Math.max(1, 2, 3, 55, 4, 6));
// expected result: 55

That's well and good, but typically when we're reaching for some real world data, we don't know all of the arguments we'd need to pass to Math.max(). But isn't that exactly the exact use case for spreading into a function?

Here's that same example, but done using Function Spread. You could imagine passing in an array of any size to Math.max now.

// could be any length with any amount of integers!
const numbers = [1, 2, 3, 55, 4, 6];
console.log(Math.max(...numbers));
// expected result: 55;

This is all fairly simple, and just to solidify the concept, here's one more example. Say you want a function that will greet you by your full name. You could reach for bracket notation:

const name = ['Joey', 'Reyes'];
function sayHi (first, last) {
  console.log(`Hey there ${first} ${last}.`);
};
sayHi(name[0], name[1]);
// expected result: "Hey there Joey Reyes.";

...but come on. That looks so clunky. Let's use Function Spread:

const name = ['Joey', 'Reyes'];
function sayHi (first, last) {
  console.log(`Hey there ${first} ${last}.`);
};
sayHi(...name);
// expected result: "Hey there Joey Reyes.";

From MDN: Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

See more examples and documentation here.

More Spread Syntax

Read more about Spread Syntax, Destructuring, and Rest here:

  1. Array Spread
  2. Function Spread
  3. Object Spread
  4. Array Destructuring
  5. Object Destructuring
  6. Rest Syntax