Spread and Rest Operators

Use ... for arrays, objects, and function parameters

#spread #rest #es6 #syntax

Spread and Rest Operators

The ... operator for expanding and collecting values.

Spread Operator

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

// Object spreading
const user = {name: 'Alice', age: 30};
const details = {city: 'NYC', country: 'USA'};
const fullUser = {...user, ...details};
console.log(fullUser);
// {name: 'Alice', age: 30, city: 'NYC', country: 'USA'}

// Function arguments
function sum(a, b, c) {
  return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));  // 6

Rest Operator

// Function parameters
function sum(...numbers) {
  return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4, 5));  // 15

// Array destructuring
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first);  // 1
console.log(rest);   // [2, 3, 4, 5]

// Object destructuring
const {name, ...otherProps} = {
  name: 'Alice',
  age: 30,
  city: 'NYC'
};
console.log(name);        // Alice
console.log(otherProps);  // {age: 30, city: 'NYC'}

Discover another handy tool from EditPDF.pro