JavaScript Spread Operator Explained

Three dots that changed JavaScript: ... The spread operator in action: Arrays: // Copy const copy = [...original] // Merge const all = [...arr1, ...arr2] // Add items const updated = [...items, newItem] Objects: // Copy const clone = { ...user } // Merge const combined = { ...defaults, ...config } // Update const modified = { ...user, age: 30 } Function calls: Math.max(...numbers) fetch(url, { ...defaultOptions, ...customOptions }) Before spread operator: const copy = original.slice() const merged = Object.assign({}, obj1, obj2) fn.apply(null, args) After spread operator: const copy = [...original] const merged = { ...obj1, ...obj2 } fn(...args) The magic: → No mutation (safer code) → Cleaner syntax → Works with any iterable → Essential for React state → Makes immutability easy Three dots. Infinite possibilities.

To view or add a comment, sign in

Explore content categories