ResourcesJavascriptGuides

Spread and rest operators [...]

Introduction

Spread and rest operators both are a powerful feature that makes your life easier while working with objects and arrays.


Spread Operator

The spread operator (...) allows you to expand an iterable (for example `array) into individual elements.

Spread in arrays

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6];
 
console.log(arr2); // Output: [1, 2, 3, 4, 5, 6]

Another, real life example:

// I don't want to mutate array so I will create copy
// with new values using spread
 
const tasks = ['learn react', 'write this article'];
 
const newTask = 'run 10km'
 
const updatedTasks = [...tasks, newTask];

Spread in objects

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
 
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }

Rest operator

The rest operator (...) allows you to condense multiple elements into a single array or object.

Rest operator in functions

function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}
 
console.log(sum(1, 2, 3, 4)); // Output: 10

Rest in arrays

In this example the rest operator condenses the remaining elements into the rest array.

const [first, second, ...rest] = [1, 2, 3, 4, 5];
 
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]

Combine Spread and Rest

Both spread and rest operators can be combined in some scenarios. Let's check example.

function multiply(multiplier, ...numbers) {
  return numbers.map(num => num * multiplier);
}
 
const nums = [1, 2, 3];
console.log(multiply(2, ...nums)); // Output: [2, 4, 6]

Best practices

  • Don't overuse!: While both are useful for code readability, as you can see while we combined them, the complexity of the code has grown a lot. Imagine more complex scenario.

  • Order: Pay attention to order when using spread and rest operators.

Resources

MDN Web docs

On this page