93. The Spread Operator (...)
The Spread Operator (...) is represented by three dots. It unpacks or 'spreads' the elements of an iterable (like an array) or the properties of an object into another array or object literal.
1. Spreading Arrays (Combining and Cloning)
It's the simplest way to create a shallow copy of an array (solving the reference issue).
javascript const arr1 = [1, 2]; const arr2 = [3, 4];
// Combining arrays const combined = [...arr1, ...arr2, 5]; // [1, 2, 3, 4, 5]
// Cloning an array (makes a new reference) const arrCopy = [...arr1]; arrCopy.push(99); console.log(arr1); // [1, 2] (original is unchanged)
2. Spreading Objects (Merging)
Spreads the key-value pairs of one object into another. Useful for updating state or configuration.
javascript const defaults = { color: 'red', size: 'M' }; const userSettings = { size: 'L', theme: 'dark' };
// Merge defaults, then overwrite with userSettings properties const finalSettings = { ...defaults, ...userSettings, border: 'none' };
/* Output: { color: 'red', size: 'L', // Overwritten theme: 'dark', border: 'none' } */