Spread and Rest Operators in JavaScript: Complete Guide with Examples
Quick Answer: The spread syntax expands values from an array or object. The rest syntax collects multiple values into one array or object. Both use three dots (...), but their purpose depends on where you use them.
Use spread to copy, combine or pass values. Use rest to collect function arguments or remaining properties.
1. Why Do We Need Spread and Rest?
Imagine Priya manages a grocery shop in Bengaluru. She maintains product lists, daily orders and customer details.
Her shop receives hundreds of orders every day. She needs to combine product lists and collect customer selections.
How can she do this without writing extra loops every time?
First, let us understand the problem without spread and rest.
The Problem Without Spread Syntax
Priya has two product lists. She wants one combined list for the checkout counter.
Example 1: Combine Two Grocery Lists Without Spread
This example manually copies each product into a new array.
const morningProducts = ["Rice", "Wheat"];
const eveningProducts = ["Milk", "Sugar"];
const allProducts = [];
for (const product of morningProducts) {
allProducts.push(product);
}
for (const product of eveningProducts) {
allProducts.push(product);
}
console.log(allProducts);
Expected output
[ 'Rice', 'Wheat', 'Milk', 'Sugar' ]
This works, but the code becomes repetitive when lists grow.
The Problem Without Rest Syntax
Now Priya wants a function that prints every product in an order.
Without rest, she must handle a fixed number of parameters or use another array.
Example 2: Handle Product Arguments Without Rest
function printProducts(productOne, productTwo, productThree) {
console.log(productOne);
console.log(productTwo);
console.log(productThree);
}
printProducts("Rice", "Milk", "Sugar");
Expected output
Rice Milk Sugar
This function expects exactly three product parameters. What if an order contains five products?
What Goes Wrong?
- Manual copying creates extra code.
- Fixed parameters make functions less flexible.
- Combining many lists becomes harder to maintain.
- Object copying can accidentally change the original object.
- Adding more values may require changing existing code.
Now think about hundreds of daily grocery orders. We need a cleaner approach.
2. What Is the Spread Operator?
Spread syntax = a way to expand values from an iterable or object.
An iterable is a value whose items can be read one by one. Arrays and strings are common examples.
Spread syntax uses three dots before the value. It looks like this: ...arrayName.
It expands the items where JavaScript expects individual values.
Combine Arrays Using Spread
Priya can combine both grocery lists with one expression.
Example 3: Combine Grocery Lists Using Spread
const morningProducts = ["Rice", "Wheat"];
const eveningProducts = ["Milk", "Sugar"];
const allProducts = [
...morningProducts,
...eveningProducts
];
console.log(allProducts);
Expected output
[ 'Rice', 'Wheat', 'Milk', 'Sugar' ]
JavaScript expands each array item into the new array. The original arrays stay unchanged.
Animation 1: How Spread Expands an Array
The following diagram uses a grocery-list flow. It shows each source list expanding into one new list.
Spread syntax — array expansion
The spread syntax reads each source item and places it into the new array.
Copy an Array Using Spread
Sometimes Priya needs a separate list for a new checkout session.
She can copy the array using spread syntax.
Example 4: Create a Shallow Array Copy
const shopProducts = ["Rice", "Milk", "Sugar"];
const checkoutProducts = [...shopProducts];
checkoutProducts.push("Tea");
console.log(shopProducts);
console.log(checkoutProducts);
Expected output
[ 'Rice', 'Milk', 'Sugar' ] [ 'Rice', 'Milk', 'Sugar', 'Tea' ]
The new array has its own list structure. Adding an item does not change the original array.
Important: Spread creates a shallow copy. Nested objects are still shared references. We will cover this limitation later.
Add Items While Copying an Array
We can add new products before or after existing items.
Example 5: Add Products at Both Ends
const shopProducts = ["Rice", "Milk"];
const updatedProducts = [
"Wheat",
...shopProducts,
"Sugar"
];
console.log(updatedProducts);
Expected output
[ 'Wheat', 'Rice', 'Milk', 'Sugar' ]
Spread an Array into Function Arguments
A function can accept separate arguments. Spread can provide array items as those arguments.
Example 6: Pass Product Prices to a Function
function calculateTotal(rice, milk, sugar) {
return rice + milk + sugar;
}
const productPrices = [60, 30, 45];
const total = calculateTotal(...productPrices);
console.log(total);
Expected output
135
Here, the array becomes three separate function arguments.
Spread a String into Characters
Strings are iterable. So spread can expand a string into individual characters.
Example 7: Expand a Product Name
const productName = "Rice";
const productLetters = [...productName];
console.log(productLetters);
Expected output
[ 'R', 'i', 'c', 'e' ]
3. Spread Syntax with Objects
JavaScript also supports spread syntax with plain objects. It copies the object's enumerable own properties into another object.
Priya stores product details in an object. She wants to create an updated product record.
Example 8: Copy and Update a Product Object
const riceProduct = {
name: "Rice",
price: 60,
category: "Groceries"
};
const discountedRice = {
...riceProduct,
price: 55
};
console.log(riceProduct);
console.log(discountedRice);
Expected output
{ name: 'Rice', price: 60, category: 'Groceries' }
{ name: 'Rice', price: 55, category: 'Groceries' }
The new object copies the existing properties. The later price value replaces the earlier price.
Merge Two Objects
Priya keeps product details and stock details separately. She can merge them into one object.
Example 9: Merge Product and Stock Details
const productDetails = {
name: "Rice",
price: 60
};
const stockDetails = {
quantity: 25,
store: "Bengaluru"
};
const completeProduct = {
...productDetails,
...stockDetails
};
console.log(completeProduct);
Expected output
{ name: 'Rice', price: 60, quantity: 25, store: 'Bengaluru' }
Which Value Wins When Properties Have the Same Name?
When two objects contain the same property, the later value wins.
Example 10: Resolve Duplicate Object Properties
const regularPrice = {
name: "Rice",
price: 60
};
const festivalPrice = {
...regularPrice,
price: 52
};
console.log(festivalPrice.price);
Expected output
52
The new price appears after the spread. So it replaces the copied price.
Animation 2: How Object Spread Works
This diagram shows how product details and stock details become one checkout record.
Object spread — property merging
Each spread copies enumerable own properties into the new object. Later properties can overwrite earlier ones.
4. What Is the Rest Operator?
Rest syntax = a way to collect remaining values into one array or object.
It also uses three dots. But it works in a different direction from spread.
Priya wants one function that accepts any number of products. She does not want fixed parameters.
Collect Function Arguments Using Rest
Rest parameters collect the remaining function arguments into an array.
Example 11: Accept Any Number of Products
function printProducts(...products) {
console.log(products);
}
printProducts(
"Rice",
"Milk",
"Sugar",
"Tea"
);
Expected output
[ 'Rice', 'Milk', 'Sugar', 'Tea' ]
The function receives four arguments. Rest collects them into the products array.
Use Normal Parameters Before Rest
Rest can collect values after normal parameters. The rest parameter must be the last parameter.
Example 12: Collect Products for a Customer
function createOrder(customerName, ...products) {
console.log("Customer:", customerName);
console.log("Products:", products);
}
createOrder(
"Priya",
"Rice",
"Milk",
"Sugar"
);
Expected output
Customer: Priya Products: [ 'Rice', 'Milk', 'Sugar' ]
Animation 3: How Rest Collects Function Arguments
Each product argument enters the function. The rest parameter collects the remaining values into one array.
Rest syntax — argument collection
Rest collects multiple arguments into one array for the function to process.
Rest in Array Destructuring
Destructuring lets us unpack values from an array. Rest collects the remaining values.
Priya wants the first product separately. She also needs all remaining products.
Example 13: Get the First Product and Remaining Products
const orderProducts = [
"Rice",
"Milk",
"Sugar",
"Tea"
];
const [firstProduct, ...remainingProducts] = orderProducts;
console.log(firstProduct);
console.log(remainingProducts);
Expected output
Rice [ 'Milk', 'Sugar', 'Tea' ]
Rest in Object Destructuring
Rest can also collect remaining object properties. This helps when we need only selected fields.
Example 14: Separate Customer Name from Other Details
const customer = {
name: "Priya",
city: "Bengaluru",
phone: "9876543210",
membership: "Gold"
};
const { name, ...otherDetails } = customer;
console.log(name);
console.log(otherDetails);
Expected output
Priya
{
city: 'Bengaluru',
phone: '9876543210',
membership: 'Gold'
}
The name property is extracted. Rest collects every remaining enumerable own property.
5. Spread vs Rest: The Main Difference
Both use three dots, but their jobs are different. Spread expands values. Rest collects values.
| Feature | Spread | Rest |
|---|---|---|
| Purpose | Expands values | Collects remaining values |
| Direction | One collection into separate values | Separate values into one collection |
| Common use | Array and object creation | Function parameters |
| Function use | Pass array items as arguments | Collect arguments into an array |
| Destructuring | Not used as an assignment target | Collects remaining array items or object properties |
| Position | Used where values are expanded | Must be last in a function parameter list |
One Example to Remember Both
Look at this function call and function definition together.
Example 15: Spread Sends Values, Rest Collects Them
function showOrder(...products) {
console.log(products);
}
const orderProducts = ["Rice", "Milk", "Sugar"];
showOrder(...orderProducts);
Expected output
[ 'Rice', 'Milk', 'Sugar' ]
Inside the call, spread expands the array. Inside the function, rest collects the arguments.
Remember this: Spread is used when sending values out. Rest is used when receiving values together.
6. Step-by-Step Code Breakdown
How Spread Works
JavaScript reads the array items or object properties.
The three dots place those values into the target location.
The surrounding array, object or function call receives the expanded values.
How Rest Works
A function or destructuring pattern receives multiple values.
Rest gathers values that were not assigned to earlier parameters or variables.
Function code or later statements can work with the resulting array or object.
7. Important Rules and Common Mistakes
Mistake 1: Thinking Spread Makes a Deep Copy
Spread copies an array or object only one level deep. Nested objects remain shared.
Example 16: Nested Objects Still Share References
const originalOrder = {
customer: "Priya",
delivery: {
city: "Bengaluru"
}
};
const copiedOrder = { ...originalOrder };
copiedOrder.delivery.city = "Mysuru";
console.log(originalOrder.delivery.city);
console.log(copiedOrder.delivery.city);
Expected output
Mysuru Mysuru
Both objects refer to the same nested delivery object. Changing it affects both.
Important: Do not treat spread as a deep-cloning tool. Use a suitable deep-copy approach when nested data must be independent.
Mistake 2: Placing Rest Before Other Parameters
A rest parameter must always be the last function parameter.
Incorrect Example
// Syntax error: rest parameter is not last
function createOrder(...products, customerName) {
console.log(products, customerName);
}
Correct Example
function createOrder(customerName, ...products) {
console.log(customerName, products);
}
createOrder("Priya", "Rice", "Milk");
Expected output
Priya [ 'Rice', 'Milk' ]
Mistake 3: Using Rest More Than Once
A function parameter list cannot contain multiple rest parameters.
Incorrect Example
// Syntax error: only one rest parameter is allowed
function createOrder(...products, ...services) {
console.log(products, services);
}
Use one rest parameter. Pass structured data when you need separate groups.
Mistake 4: Expecting Rest to Include Earlier Values
Rest collects only the values that remain after earlier assignments.
Example 17: Rest Collects Only Remaining Array Items
const products = ["Rice", "Milk", "Sugar"];
const [first, ...others] = products;
console.log(first);
console.log(others);
Expected output
Rice [ 'Milk', 'Sugar' ]
Mistake 5: Forgetting Property Override Order
When object properties repeat, the last copied or written value wins.
Example 18: Put the Preferred Value Last
const product = { name: "Rice", price: 60 };
const updatedProduct = {
price: 50,
...product
};
console.log(updatedProduct.price);
Expected output
60
The spread comes after the new price. So the original price overwrites it.
To keep the new price, put it after the spread.
8. Useful Real-World Applications
Application 1: Add a Product to a Cart
Use spread to create a new cart array. This avoids changing the existing array.
Example 19: Add a New Grocery Product
const cart = ["Rice", "Milk"];
const updatedCart = [...cart, "Sugar"];
console.log(updatedCart);
Expected output
[ 'Rice', 'Milk', 'Sugar' ]
Application 2: Calculate a Variable Number of Prices
Use rest when a function needs to accept any number of prices.
Example 20: Calculate the Total Order Amount
function calculateOrderTotal(...prices) {
return prices.reduce(
(total, price) => total + price,
0
);
}
console.log(
calculateOrderTotal(60, 30, 45, 25)
);
Expected output
160
Application 3: Update Customer Details
Use object spread to preserve existing customer details. Then override only the required property.
Example 21: Update a Customer Address
const customer = {
name: "Priya",
city: "Bengaluru",
membership: "Gold"
};
const updatedCustomer = {
...customer,
city: "Mysuru"
};
console.log(updatedCustomer);
Expected output
{ name: 'Priya', city: 'Mysuru', membership: 'Gold' }
9. Performance and Development Considerations
- Small collections: Spread and rest make common operations easy to read.
- Large collections: Repeated copying can use extra memory and processing time.
- Nested data: Spread does not create independent nested objects.
- Object merging: Property order matters when keys repeat.
- Function design: Rest is useful when a function accepts a variable number of arguments.
- Maintainability: Use clear parameter names so collected values are easy to understand.
Spread creates a new array or object when used in those expressions. Avoid repeatedly copying very large collections inside performance-critical loops.
10. Interview Questions and Answers
Question 1: What Is the Difference Between Spread and Rest?
What the interviewer wants: They want to check whether you understand both uses of the three-dot syntax.
Strong answer: "Spread expands values from an array or object. Rest collects remaining values into an array or object. I use spread to combine grocery product lists. I use rest to collect products passed to an order function."
Question 2: Can We Use Spread to Copy an Array?
Strong answer: "Yes. We can use the spread syntax inside a new array. It creates a shallow copy. The new array has a separate outer structure. Nested objects are still shared."
Question 3: What Is a Rest Parameter?
Strong answer: "A rest parameter collects the remaining function arguments into an array. It helps when the number of arguments can change. It must be the last parameter in the function."
Question 4: Can We Use Spread with Objects?
Strong answer: "Yes. Object spread copies enumerable own properties into a new object. We can use it to copy or merge product details. If keys repeat, the later value wins."
Question 5: Is Spread a Deep Copy?
Strong answer: "No. Spread creates a shallow copy. It copies the first level. Nested objects still point to the same references. I use a proper deep-copy method when independent nested data is needed."
Question 6: Can We Use Rest in Array Destructuring?
Strong answer: "Yes. We can assign the first few array items to variables. Rest collects the remaining items into a new array. The rest element must be last in the destructuring pattern."
Junior, Senior and Architect Expectations
| Level | Expected understanding |
|---|---|
| Junior | Explain spread and rest with simple array examples. |
| Senior | Explain object merging, shallow copies and parameter handling. |
| Architect | Discuss immutability, nested references, memory costs and API design. |
11. Hands-On Practice
Beginner Exercise: Combine Product Lists
Priya has two product lists. Use spread to combine them.
Starting data
const firstList = ["Rice", "Wheat"];
const secondList = ["Milk", "Tea"];
// Create combinedList using spread.
// Print the result.
Expected result: ["Rice", "Wheat", "Milk", "Tea"]
Intermediate Exercise: Build a Flexible Order Function
Create a function named createOrder. It should receive a customer name and any number of products.
- Use a normal parameter for the customer name.
- Use a rest parameter for the products.
- Print both values.
- Test the function with at least four products.
Advanced Exercise: Update a Nested Customer Object
Create a customer object with name, city and delivery details. Copy it using spread.
- Change the customer's city in the new object.
- Keep the original city unchanged.
- Change the nested delivery city.
- Check whether the original nested city also changes.
- Explain why the nested value behaves differently.
12. Frequently Asked Questions
Can Spread Be Used with Arrays?
Yes. Spread expands array items into a new array or function call. It also works with other iterable values, such as strings.
Can Spread Be Used with Objects?
Yes. Object spread copies enumerable own properties into a new object.
Can We Use Rest in a Function?
Yes. A rest parameter collects the remaining arguments into an array. It must be the final parameter.
Are Spread and Rest Different Operators?
They are commonly called operators, but JavaScript documentation describes them as spread syntax and rest syntax. The three-dot syntax has different behavior based on its position.
Does Spread Change the Original Array?
No. Spreading an array into a new array does not change the original array. However, nested object references may still be shared.
Can We Use Rest with Object Destructuring?
Yes. It collects the remaining enumerable own properties into a new object. The rest property must be last in the destructuring pattern.
13. Next Steps and Community
Try It Yourself
Run every example in your browser console or a JavaScript playground. Change the product names and values. Observe how the output changes.
Explore Further
Share Your Knowledge
Try these examples in your own projects. Share your approach and discuss other solutions. Your explanation may help another developer learn these concepts.
Key Takeaway: Spread expands values. Rest collects remaining values. Learn where each syntax belongs, and remember that spread creates shallow copies.
Upgradix by Shrash Studio — Learn Technology. Build Your Future.