ES6 – Spread operator in functions

Hi, the spread operator is part of ES6 and is represented by “” token, spread operator splits an iterable object into individual values.

First let me define an “iterable“: is an object that contains a group of values and this implements a ES6 iterable protocol that let us to go through every value, for example: an Array is an example of iterable.

The spread operator also is used wherever multiple function arguments or multiple elements.

Let’s see how spread operator works in functions:

Usually for pass values of the an array as function argument we use the .appy() method like this:

// Array with some data
const data = [10, 5];

// Function that return a subtraction
const myFunction = (a, b) => {
  return a - b;
};

// Calling myFunction and passing the values of the array as a parameter using the .apply() method
const result = myFunction.apply(null, data);

console.log("result --->", result);

Result:

Nice, but ES6 provide a easy way to do the same; and this is using “Spread operator” so the same example with Spread operator will be like this:

// Array with some data
const data = [10, 5];

// Function that return a subtraction
const myFunction = (a, b) => {
  return a - b;
};

// Calling myFunction and passing the values of the array as a parameter using the .apply() method
const result = myFunction(...data);

console.log("result --->", result);

Result: if you see the code we just call the function like this myFunction(…data); and the result is the same.

By Cristina Rojas.