JavaScript Notes
Master the JavaScript spread operator (...): copy arrays/objects, merge data, pass arguments, shallow vs deep copy, and real-world patterns with clear examples.
What is the Spread Operator?
The spread operator (...) expands (spreads out) an iterable (array, string, object) into individual elements. It's like opening a box and tipping everything out.
Think of it like a magic blender lid: when you spread an array into a function, it's like individually dropping each fruit in —sum(...[1,2,3])becomessum(1, 2, 3).
Spread in Arrays
Copy an Array (Shallow)
[ 1, 2, 3, 4, 5 ] [ 1, 2, 3, 4, 5, 6 ]
Merge / Concatenate Arrays
[ 'HTML', 'CSS', 'JavaScript', 'React', 'Node.js', 'Express', 'MongoDB' ]
Convert String to Array of Characters
[ 'H', 'e', 'l', 'l', 'o' ]
Find Max/Min from Array
95 62
Spread in Objects
Copy an Object (Shallow)
const user = { name: "Riya", age: 22, city: "Delhi" };
const userCopy = { ...user };
userCopy.city = "Mumbai";
console.log(user.city); // original unchanged
console.log(userCopy.city); // copy changedDelhi Mumbai
Merge Two Objects
const defaults = { theme: "light", lang: "en", fontSize: 14 };
const overrides = { theme: "dark", fontSize: 18 };
const merged = { ...defaults, ...overrides };
console.log(merged);{ theme: 'dark', lang: 'en', fontSize: 18 }Add/Override Specific Properties (Immutable Pattern)
const product = { id: 101, name: "Phone", price: 15000, stock: 50 };
// Update price without mutating original
const updatedProduct = { ...product, price: 12000, onSale: true };
console.log(product); // original preserved
console.log(updatedProduct);{ id: 101, name: 'Phone', price: 15000, stock: 50 }
{ id: 101, name: 'Phone', price: 12000, stock: 50, onSale: true }Spread in Function Calls
Aman is a Developer at Google
Spread vs Rest Operator — The Key Difference
Both use ... but do opposite things:
| Feature | Spread ... | Rest ... |
|---|---|---|
| What it does | Expands iterable into elements | Collects elements into array |
| Where used | Function calls, array/object literals | Function parameters, destructuring |
| Direction | One → Many | Many → One |
| Example | fn(...arr) | function fn(...args) |
| Result | Individual elements | Array |
5 15
Shallow Copy — The Limitation
Spread creates a shallow copy — nested objects are still shared by reference:
const original = {
name: "Neha",
address: { city: "Pune", pincode: 411001 }
};
const copy = { ...original };
copy.name = "Tara"; // ✅ doesn't affect original
copy.address.city = "Mumbai"; // ❌ AFFECTS original too!
console.log(original.name); // Neha (unaffected)
console.log(original.address.city); // Mumbai (affected!)Neha Mumbai
For a true deep copy: structuredClone(obj) or JSON.parse(JSON.stringify(obj))
const deepCopy = structuredClone(original);
deepCopy.address.city = "Chennai";
console.log(original.address.city); // still Mumbai — deep copy is independentMumbai
Real World Use Cases 🌍
1. Redux-style Immutable State Update
const state = { user: "Priya", count: 5, loading: false };
const newState = { ...state, count: state.count + 1, loading: true };
console.log(newState);{ user: 'Priya', count: 6, loading: true }2. Safe Array Operations (No Mutation)
[ 'Buy groceries', 'Read book', 'Exercise' ] [ 'Buy groceries', 'Read book', 'Exercise', 'Learn JavaScript' ]
3. Flatten and Combine
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Mistakes ❌
1. Spreading an object into an array
2. Thinking spread is a deep copy
// ❌ Assumption
const config = { db: { host: "localhost" } };
const copy = { ...config };
copy.db.host = "production"; // mutates original!
// ✅ Deep copy
const safeCopy = structuredClone(config);3. Property override order confusion
// ❌ Wrong order — original overwrites update
const update = { price: 99 };
const product = { price: 150, name: "Book" };
const result = { ...update, ...product }; // product overwrites update
console.log(result.price); // 150, not 99!
// ✅ Correct — put override LAST
const correct = { ...product, ...update };
console.log(correct.price); // 99 ✅Interview Questions 🎯
Q1. What does the spread operator do? > It expands an iterable (array, string, object) into individual elements. In arrays it spreads elements; in objects it spreads key-value pairs.
Q2. What is the difference between spread and rest operators? > Both use ... but opposite directions. Spread expands one into many (in calls/literals). Rest collects many into one array (in parameters/destructuring).
Q3. Does the spread operator perform a deep copy? > No. Spread performs a shallow copy. Top-level properties get new copies, but nested objects still share the same reference.
Q4. How do you merge two objects with spread? > const merged = { ...obj1, ...obj2 }. If both have the same key, the last one wins (rightmost object's value is kept).
Q5. Can you spread an object into an array? > No, plain objects are not iterable. You can spread arrays into arrays, or use Object.values(obj) to get an array first.
Q6. How is spread useful for immutable updates? > Instead of mutating: obj.key = newVal, you create a new object: { ...obj, key: newVal }. The original object is untouched.
Q7. What is the result of spreading a string with [...str]? > It splits the string into an array of individual characters: [..."Hello"] → ["H","e","l","l","o"].
Key Takeaways 🏁
...in a call/literal = Spread (expand)...in parameters/destructuring = Rest (collect)- Spread creates shallow copies — nested objects are still shared references
- Object spread: last property wins when keys conflict
- Use spread for immutable updates — create new arrays/objects instead of mutating
Math.max(...array)is a clean pattern for max/min withoutapply- For deep copies, use
structuredClone()(ES2022) instead of spread
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Spread Operator (...) - Complete Guide with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, objects, spread, operator
Related JavaScript Master Course Topics