Learning ES6 JavaScript Spread Operator

How you can use JavaScript spread operator on arrays and objects

Posted on January 06, 2021


JavaScript spread operator (...) is used to expand the values of an iterable ( usually an array or an object) so that you can pass those values as arguments of a function. For example, let’s say you have a function that calculates the sum of three numbers:

function sumThree(a, b, c){
  return a+b+c;
}

Next, you want to pass an array of three numbers into the function. You can use the spread operator on the function:

let scores = [7, 9, 7];

let summedNumber = sumThree(...scores);
// The same as sumThree(7, 9, 7); 

console.log(summedNumber);
// output is 23

You can merge two or more arrays using spread operator:

let firstArray = [4, 5];
let secondArray = [9, 10];

let mergedArray = [...firstArray, ...secondArray];
// mergedArray is [4, 5, 9, 10]

You can also use this merging technique to objects:

let firstObject = { name: "Jack" };
let secondObject = { age: 19 };

let mergedObject = {...firstObject, ...secondObject};
// mergedObject is { name: "Jack", age: 19 }

But the spread operator can’t be used to pass object properties into a function:

let user = {
  name: "Jack",
  age: 27
};

function greetings(name, age){
  console.log(`Hello, my name is ${name} and I'm ${age} years old`);
}

greetings(...user);
// Will cause an error
// Uncaught TypeError: Found non-callable @@iterator at <anonymous>:1:1

Spread operator use cases

The spread operator can be used on both Math.min and Math.max method to find the value inside an array.

It also can be used on React to pass props between components.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more
JavaScript Introduction Book