JavaScript Spread vs Rest Operator
JavaScript array spread operator example showing array expansion
If you’ve been working with JavaScript ES6+ features, you’ve likely come across the three-dot syntax ...
used in different contexts. This syntax can either be the spread operator or the rest operator, depending on how it's used. Although they look identical, their purposes are quite different.
In this article, we’ll explore the differences between the JavaScript spread and rest operators, how they work, and when to use each—with clear code examples.
The spread operator is used to expand an iterable (like an array, object, or string) into individual elements. It’s commonly used when you need to pass elements individually instead of as a group.
const newArray = [...oldArray];
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
const result = sum(...numbers);
console.log(result); // Output: 6
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // Output: { a: 1, b: 2, c: 3 }
The rest operator is used to collect multiple elements into a single array. It’s especially useful when working with functions that accept an unknown number of arguments or when destructuring arrays or objects.
function example(...args) {
// args is an array
}
function myFunc(first, ...rest) {
console.log(first); // Output: 1
console.log(rest); // Output: [2, 3, 4]
}
myFunc(1, 2, 3, 4);
const [first, second, ...remaining] = [1, 2, 3, 4, 5];
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(remaining); // Output: [3, 4, 5]
Feature | Spread Operator | Rest Operator |
---|---|---|
Purpose | Expands elements | Collects elements |
Syntax |
...iterable |
...restParam |
Placement | Used on the right (e.g., assignment, function call) | Used on the left (e.g., function params, destructuring) |
Common Use Cases | Array copy, merging, function calls | Variadic functions, destructuring |
While the spread and rest operators use the same syntax (...
), they serve opposite functions:
The spread operator expands elements of an iterable.
The rest operator collects multiple values into an array.
You want to pass or copy multiple values.
You're merging arrays or objects.
You're handling variable function arguments.
You need to gather remaining elements during destructuring.
Understanding the difference between spread vs rest operator in JavaScript is crucial for writing clean, concise, and modern code. By mastering both, you can simplify tasks involving arrays, objects, and function parameters.
Learn more on Javascript - Javascript Tutotial