DEV Community

Cover image for JS Spread syntax
Henry Arbolaez
Henry Arbolaez

Posted on • Updated on

JS Spread syntax

JS Spread syntax

Learn the basics of the JavaScript Spread Operator


The spread syntax was introduced with ES6. Is a great tool to make your javascript code a little more clean and readable.

MDN definition:

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.

Let start with object cloning them:

const person = {
  firstName: 'Henry',
  lastName: 'Arbolaez',
};

const personWithAge = { ...person, age: 27 };
Enter fullscreen mode Exit fullscreen mode

Merging two objects:

const profession = {
  career: 'Software Engineer',
  work: 'Lavu',
};

const personalInformation = { ...personWithAge, ...profession };

/**
 * personalInformation becomes
  age: 27;
  career: 'Software Engineer';
  firstName: 'Henry';
  lastName: 'Arbolaez';
  work: 'Lavu';
*/
Enter fullscreen mode Exit fullscreen mode

We can also utilize the spread syntax to copy array's:

const numbers = [1, 2, 3, 4, 5];
const copiedNumbers = [...numbers];

// copiedNumbers becomes [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

A better way merging array's

const numbers = [1, 2, 3];
const numbers2 = [6, 7, 8];

const numbers3 = [...numbers, ...numbers2];

// numbers3 becomes [1, 2, 3, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

We can also assign some remining values using ...rest:

// note `rest` can be name anything you'll like
const [a, b, ...rest] = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

// a    => "a"
// b    => "b"
// rest => ['c', 'd', 'e', 'f', 'g']
Enter fullscreen mode Exit fullscreen mode

Passing parameters with spread syntax

const dateArray = [2019, 1, 15];
const date = new Date(...dateArray);
// @return Fri Feb 15 2019 00:00:00 GMT-0500 (Eastern Standard Time)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)