π€ JavaScript Spread Operator (...) Explained
Category: js / general-concepts
Difficulty: easy
The spread operator (...) in JavaScript is used to expand elements of an iterable (like an array or object) into individual elements. π 1. Expanding Arrays Example: Expanding an Array into Function Arguments [code example] β
The spread operator unpacks the array elements into separate arguments. Example: Combining Arrays [code example] β
Alternative to concat() , creating a new merged array. Example: Copying Arrays (Shallow Copy) [code example] β
Prevents accidental mutation by creating a new array instead of referencing the original. π 2. Using Spread with Objects Example: Merging Objects [code example] β
Alternative to Object.assign() , creating a new object. Example: Overwriting Object Properties [code example] β
The b property in objA is overwritten by b in objB. π 3. Spread vs Rest (...) Operator Spread (...) Expands elements Function calls, arrays, objects sum(...[1,2,3])βsum(1,2,3) Example: Spread vs Rest in Functions [code example] β
Spread "spreads out", Rest "gathers in". π 4. Practical Use Cases 1οΈβ£ Clone and Modify Objects [code example] β
Useful for immutable state updates (React, Redux, etc.). 2οΈβ£ Remove an Object Property [code example] β
Removes city from person without modifying the original object. 3οΈβ£ Convert a String into an Array [code example] β
Useful for string manipulation. π Summary Example sum(...[1,2,3]) [...arr1, ...arr2] [...original] { ...obj1, ...obj2 } { ...user, age: 30 } [..."Hello"] π‘ Final Thought: The spread operator (...) is one of JavaScript's most powerful tools for working with arrays, objects, and function arguments in a clean, concise way. <!-- quiz-start --> Q1: What does the spread operator do when used with an array? [ ] Combines arrays by reference [x] Expands array elements into individual elements [ ] Creates a deep copy of nested objects [ ] Removes duplicate elements Q2: What is the result of { ...{ a: 1, b: 2 }, ...{ b: 3, c: 4 } }? [ ] { a: 1, b: 2, c: 4 } [x] { a: 1, b: 3, c: 4 } [ ] { a: 1, b: [2, 3], c: ...