Introduction to Spread and Rest Operators
JavaScript's ...
(three dots) syntax is a powerful and flexible feature that behaves differently based on the context. It is used as:
- Spread Operator: to expand or unpack elements.
- Rest Operator: to collect or pack elements.
Spread Operator
The spread operator ...
allows you to expand elements of an array or object into individual elements.
1. Copying Arrays
const original = [1, 2, 3];
const copy = [...original];
console.log(copy);
Output:
[1, 2, 3]
This creates a shallow copy of the array. It is much safer than assigning copy = original
, which just points to the same reference.
2. Merging Arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged);
Output:
[1, 2, 3, 4]
You can merge multiple arrays into one using the spread operator.
3. Spreading in Function Calls
const numbers = [5, 6, 7];
console.log(Math.max(...numbers));
Output:
7
This is useful when passing an array as individual arguments to a function.
4. Copying and Merging Objects
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj);
Output:
{ a: 1, b: 3, c: 4 }
Note: Later properties overwrite earlier ones in case of conflict.
Rest Operator
The rest operator also uses ...
, but instead of expanding, it gathers multiple elements into a single array or object. Its main use is in function parameters or object/array destructuring.
1. Rest in Function Parameters
function sum(...nums) {
return nums.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4));
Output:
10
Question: Why can't we just define four parameters?
Answer: Because rest makes the function flexible—it can handle any number of arguments.
2. Rest in Array Destructuring
const [first, ...rest] = [10, 20, 30, 40];
console.log(first); // 10
console.log(rest); // [20, 30, 40]
Output:
10 [20, 30, 40]
This is useful when you want to extract specific elements and collect the remaining ones.
3. Rest in Object Destructuring
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(a); // 1
console.log(others); // { b: 2, c: 3 }
Output:
1 { b: 2, c: 3 }
This helps separate one key from the rest of the object.
Points to Remember
...spread
unpacks arrays or objects....rest
packs elements into arrays or objects.- Spread is often used in copying and merging, while rest is useful in handling dynamic arguments and destructuring.
Practice Question
Question: What will the following code output?
const arr = [1, 2, 3];
const newArr = [0, ...arr, 4];
console.log(newArr);
Answer:
[0, 1, 2, 3, 4]
Both spread and rest are essential tools in modern JavaScript, enabling cleaner, more expressive code.