Problem Statement
Explain the spread operator. What are its common use cases in JavaScript?
Explanation
The spread operator uses three dots to expand an iterable like array or object into individual elements.
For arrays, it expands elements for function arguments, copying arrays, or combining arrays.
For objects, it copies properties and can be used for merging objects, with later properties overwriting earlier ones.
Spread creates shallow copies, meaning nested objects or arrays are still referenced.
It provides cleaner syntax compared to older methods like concat or Object assign.
Common use cases:
Passing array as function arguments. Cloning arrays or objects. Merging multiple arrays or objects. Converting iterables like strings into arrays.
Understanding spread operator is essential for modern JavaScript as it is widely used in React and other frameworks.
Code Solution
SolutionRead Only
// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1,2,3,4,5,6]
// Copy array
const original = [1, 2, 3];
const copy = [...original];
copy.push(4); // Does not affect original
// Function arguments
const numbers = [5, 10, 15];
console.log(Math.max(...numbers)); // 15
// Same as: Math.max(5, 10, 15)
// Object spreading
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // {a:1, b:2, c:3, d:4}
// Override properties
const user = { name: 'John', age: 30 };
const updated = { ...user, age: 31 }; // age overwritten
// String to array
const str = 'hello';
const chars = [...str]; // ['h','e','l','l','o']
// Add elements while spreading
const nums = [2, 3, 4];
const extended = [1, ...nums, 5]; // [1,2,3,4,5]
// Shallow copy warning
const nested = { x: 1, y: { z: 2 } };
const shallowCopy = { ...nested };
shallowCopy.y.z = 3; // Also changes nested.y.z!