Sobes.tech
Junior

What are the spread and rest operators used for in JavaScript?

sobes.tech AI

Answer from AI

The spread operator (...) is used to "expand" iterable objects (such as arrays or strings) into places where zero or more arguments (when calling functions) or elements (when creating arrays) are expected. It is also used to merge object properties into a new object.

// Using spread in function calls
const numbers = [1, 2, 3];
console.log(...numbers); // 1 2 3

// Using spread to merge arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combinedArr = [...arr1, ...arr2]; // [1, 2, 3, 4]

// Using spread to merge objects
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }

The rest operator (...) is used in function parameter syntax to gather all remaining arguments into an array. This allows a function to accept an indefinite number of arguments. It is also used in destructuring arrays or objects to gather the remaining elements or properties.

// Using rest in function parameters
function sum(...args) {
  // args is now an array [1, 2, 3]
  return args.reduce((total, current) => total + current, 0);
}
console.log(sum(1, 2, 3)); // 6

// Using rest in array destructuring
const [first, second, ...restOfArray] = [1, 2, 3, 4, 5];
// first = 1, second = 2, restOfArray = [3, 4, 5]

// Using rest in object destructuring
const { a, b, ...restOfObject } = { a: 1, b: 2, c: 3, d: 4 };
// a = 1, b = 2, restOfObject = { c: 3, d: 4 }

Main difference:

  • Spread "expands" elements or properties.
  • Rest "collects" elements or properties into an array/object.