JavaScript ES6 introduced two powerful operators that look the same but behave differently depending on usage:
- Spread Operator (...)
- Rest Operator (...)
Spread expands values, and Rest collects values.
What is the Spread Operator?
The Spread Operator is used to expand elements of an array, object, or iterable into individual elements.
Syntax
...iterableSpread Operator with Arrays
Copy an Array
const arr1 = [1, 2, 3];const arr2 = [...arr1];
console.log(arr2); // [1, 2, 3]- Creates a shallow copy
- Avoids reference issues
Merge Arrays
const a = [1, 2];const b = [3, 4];
const result = [...a, ...b];console.log(result);Add Elements to an Array
const numbers = [2, 3];const newNumbers = [1, ...numbers, 4];
console.log(newNumbers);Spread Operator with Objects
const user = { name: "Nikhil", age: 25 };const details = { city: "Indore" };
const combined = { ...user, ...details };
console.log(combined);Object merging made simple
Override Properties
const user = { name: "Rahul", age: 20 };
const updatedUser = { ...user, age: 25 };
console.log(updatedUser);Spread Operator in Function Calls
function add(a, b, c) { return a + b + c;}
const nums = [1, 2, 3];console.log(add(...nums));What is the Rest Operator?
The Rest Operator is used to collect multiple values into a single variable.
Syntax
Rest Operator in Functions
Array Example
function fn(...args) { // args is an array}Rest Operator in Functions
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0);}
console.log(sum(1, 2, 3, 4));- Accepts unlimited arguments
- Stores them as an array
Rest Operator in Destructuring
Array Example
const numbers = [1, 2, 3, 4];
const [first, ...rest] = numbers;
console.log(first); // 1console.log(rest); // [2, 3, 4]Object Example
const user = { name: "Anjali", age: 22, city: "Delhi"};
const { name, ...otherDetails } = user;
console.log(otherDetails);Real-World Use Cases
- Cloning state in React
- Merging configurations
- Handling dynamic function arguments
- Updating immutable data
Two Minute Drill
- Spread operator expands values
- Rest operator collects values
- Spread is used in arrays, objects, function calls
- Rest is used in function parameters and desctructuring
- Both introduced in ES6
- Makes code cleaner and flexible
