Spread & Rest Operators
The spread and rest operators use the same ... syntax, but they are used for different purposes in JavaScript.
What are Spread & Rest Operators?
The spread operator expands the elements of an array or the properties of an object.
The rest operator collects multiple values into a single array.
Simple Definition
Spread (...) means "expand or unpack values".
Rest (...) means "collect or pack values".
Spread expands values, while Rest collects values.
Spread vs Rest
| Feature | Spread | Rest |
|---|---|---|
| Syntax | ... | ... |
| Purpose | Expands values | Collects values |
| Common Use | Arrays / Objects | Function parameters |
| Direction | Unpack | Pack |
Example 1: Spread with Arrays
The spread operator can copy the elements of one array into another array.
let numbers = [10, 20, 30];
let newNumbers = [...numbers, 40, 50];
console.log(newNumbers);
Example 2: Combining Arrays
let first = [1, 2, 3];
let second = [4, 5, 6];
let combined = [...first, ...second];
console.log(combined);
Example 3: Spread with Objects
let student = {
name: "Rahul",
age: 22
};
let updatedStudent = {
...student,
course: "JavaScript"
};
console.log(updatedStudent);
age: 22
course: JavaScript
Example 4: Rest Parameters
Rest parameters collect multiple arguments into an array.
function sum(...numbers) {
let total = 0;
for (let number of numbers) {
total = total + number;
}
return total;
}
console.log(sum(10, 20, 30));
Example 5: Rest with First Parameter
function showStudent(name, ...subjects) {
console.log("Name:", name);
console.log("Subjects:", subjects);
}
showStudent("Amit", "JavaScript", "HTML", "CSS");
Subjects: JavaScript, HTML, CSS
Important Points
• Spread operator expands or unpacks values.
• Rest operator collects multiple values.
• Both use the ... syntax.
• Rest parameters are commonly used in functions.
Summary
The spread operator is useful for expanding arrays and objects, while the rest operator is useful for collecting multiple values into an array. Both use the same three-dot ... syntax.