Problem Statement
What does the spread operator (...) do?
Explanation
The spread operator expands an iterable like an array or object into individual elements.
For arrays, it spreads elements for function arguments, copying, or combining arrays.
For objects, it spreads properties for copying or merging objects.
Spread creates shallow copies, not deep copies. Nested objects are still referenced.
It provides cleaner syntax than older methods like concat or Object.assign.
Spread is one of the most useful ES6 features for working with arrays and objects.
Code Solution
SolutionRead Only
// ARRAY SPREAD
// Copy array
const arr1 = [1, 2, 3];
const arr2 = [...arr1];
arr2.push(4);
console.log(arr1); // [1, 2, 3] (unchanged)
console.log(arr2); // [1, 2, 3, 4]
// Combine arrays
const nums1 = [1, 2];
const nums2 = [3, 4];
const combined = [...nums1, ...nums2];
console.log(combined); // [1, 2, 3, 4]
// Add elements while spreading
const items = [2, 3];
const extended = [1, ...items, 4, 5];
console.log(extended); // [1, 2, 3, 4, 5]
// Function arguments
const numbers = [5, 10, 15];
console.log(Math.max(...numbers)); // 15
// Same as: Math.max(5, 10, 15)
// String to array
const str = 'hello';
const chars = [...str];
console.log(chars); // ['h', 'e', 'l', 'l', 'o']
// OBJECT SPREAD
// Copy object
const user = {name: 'John', age: 30};
const userCopy = {...user};
userCopy.age = 31;
console.log(user.age); // 30 (unchanged)
// Merge objects
const defaults = {theme: 'light', lang: 'en'};
const settings = {theme: 'dark'};
const config = {...defaults, ...settings};
console.log(config); // {theme: 'dark', lang: 'en'}
// Later properties override earlier ones
// Add properties while spreading
const person = {name: 'John'};
const employee = {...person, role: 'Developer', id: 123};
console.log(employee);
// {name: 'John', role: 'Developer', id: 123}
// SHALLOW COPY WARNING
const original = {
name: 'John',
address: {city: 'NYC'}
};
const copy = {...original};
copy.address.city = 'LA';
console.log(original.address.city); // 'LA' (changed!)
// Nested objects are still referenced
// PRACTICAL EXAMPLES
// React state updates
const state = {count: 0, user: {name: 'John'}};
const newState = {...state, count: state.count + 1};
// Array operations
const todos = ['Task 1', 'Task 2'];
const withNew = [...todos, 'Task 3'];
const withoutFirst = todos.slice(1); // or [...todos.slice(1)]
// Remove item by index
const arr = [1, 2, 3, 4, 5];
const index = 2;
const removed = [...arr.slice(0, index), ...arr.slice(index + 1)];
console.log(removed); // [1, 2, 4, 5]