J

Spread & Rest Operators

JavaScript syntax guide

Spreading and collecting values with ... operator

Spread & Rest Operators

Spreading and collecting values with ... operator

JavaScript spread & rest operators (javascript)
        
          // Spread operator with arrays
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5, 6];
console.log(moreNumbers); // [1, 2, 3, 4, 5, 6]

// Copying arrays
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original, copy); // [1, 2, 3], [1, 2, 3, 4]

// Spread with objects
const person = { name: 'John', age: 25 };
const updatedPerson = { ...person, city: 'New York' };
console.log(updatedPerson); // { name: 'John', age: 25, city: 'New York' }

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

// Rest operator in function parameters
function sum(first, ...rest) {
  return rest.reduce((acc, num) => acc + num, first);
}
console.log(sum(1, 2, 3, 4)); // 10

// Rest in array destructuring
const [first, second, ...remaining] = [1, 2, 3, 4, 5];
console.log(first, second, remaining); // 1, 2, [3, 4, 5]

// Rest in object destructuring
const { a, b, ...others } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a, b, others); // 1, 2, { c: 3, d: 4 }
        
      

Explanation

The spread operator (...) expands iterables into individual elements, while the rest operator collects multiple elements into an array or object.

Common Use Cases

  • Array manipulation
  • Object merging
  • Function arguments
  • Immutable updates

Related JavaScript Syntax

Master Spread & Rest Operators in JavaScript

Understanding spread & rest operators is fundamental to writing clean and efficient JavaScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using spread & rest operators effectively in your JavaScript projects.

Key Takeaways

  • Array manipulation
  • Object merging
  • Function arguments