JavaScript gives us powerful tools to work with data more easily—and two of the most useful are the spread (...) and rest (...) operators.
Even though they look the same, they behave very differently depending on where you use them. Let’s break it down step by step.
What the Spread Operator Does
The spread operator is used to expand (spread out) values.
Think of it like unpacking items from a box.
Example with Arrays
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers);
// [1, 2, 3, 4, 5]
Here, ...numbers takes each element and expands it into the new array.
What the Rest Operator Does
The rest operator does the opposite—it collects multiple values into one.
Think of it like packing items into a box.
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
// 10
...nums collects all arguments into a single array.
Using Spread with Arrays and Objects
Array
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined);
// [1, 2, 3, 4]
Objects:
const user = { name: "Alice", age: 25 };
const updatedUser = {
...user,
age: 26
};
console.log(updatedUser);
// { name: "Alice", age: 26 }
Spread is commonly used to copy and update data without modifying the original.
Use Cases:
- Copying Arrays (Without Mutation)
const original = [1, 2, 3];
const copy = [...original];
- Merging Objects
const defaults = { theme: "light" };
const settings = { theme: "dark", fontSize: 16 };
const finalSettings = { ...defaults, ...settings };
- Passing Arguments to Functions
const nums = [5, 10, 15];
Math.max(...nums); // 15
- Extracting Values with Rest
const [first, ...others] = [10, 20, 30, 40];
console.log(first); // 10
console.log(others); // [20, 30, 40]
Top comments (0)