DEV Community

Cover image for ... Spread/Rest Operator
jrob112
jrob112

Posted on • Updated on

... Spread/Rest Operator

The spread and rest operators are two features of JavaScript that were introduced in ES6. They can be used to simplify your code and make it more readable.

Spread Operator
The spread operator (...) allows you to expand an iterable datatype (such as an array or string) into its individual elements. This can be useful for a variety of tasks, such as copying arrays, merging objects, and creating new arrays from existing ones.

Here are a few examples of how to use the spread operator:

// Copy an array
const numbers = [1, 2, 3, 4, 5];
const copy = [...numbers];
// same as copy = [1, 2, 3, 4, 5]

// Merge two objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const mergedObj = { ...obj1, ...obj2 };
// same as mergedObj = {a: 1, b: 2, c: 3, d: 4}

// Create a new array from existing ones
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const allNumbers = [...numbers1, ...numbers2];
// same as allNumbers [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Rest Operator
The rest operator (...) allows you to collect the rest of the argument passed to a function into an array. This can be useful for mutliple tasks, such as creating functions that can accept one parameter that takes more than one argument and destructuring arrays.

Here are a few examples of how to use the rest operator:

// Create a function that can accept a variable number of arguments
function add(...numbers) {
  let sum = 0;
  for (const number of numbers) {
    sum += number;
  }
  return sum;
}
// add(1, 2, 3, 4) becomes add([1, 2, 3, 4])

// Destructure an array
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
// same as [1, 2, [3, 4, 5]]
Enter fullscreen mode Exit fullscreen mode

Since 2015, the use of the rest and spread operators have allowed very useful ways to manipulate data. The ability to use ... in the place of combining loops and methods saves time.

Top comments (0)