J

Spread & Rest Operatoren

JavaScript Syntax Guide

Werte mit ... Operator ausbreiten und sammeln

Spread & Rest Operatoren

Werte mit ... Operator ausbreiten und sammeln

JavaScript spread & rest operatoren (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

Der Spread-Operator (...) erweitert Iterables zu einzelnen Elementen, während der Rest-Operator mehrere Elemente in einem Array oder Objekt sammelt.

Common Use Cases

  • Array-Manipulation
  • Objekt-Zusammenführung
  • Funktionsargumente
  • Unveränderliche Updates

Related JavaScript Syntax

Master Spread & Rest Operatoren in JavaScript

Understanding Spread & Rest Operatoren 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 Operatoren effectively in your JavaScript projects.

Key Takeaways

  • Array-Manipulation
  • Objekt-Zusammenführung
  • Funktionsargumente