JavaScript Destructuring, Spread, and Rest Operators
Destructuring, spread, and rest are three closely related ES6 features that make working with arrays and objects cleaner and more efficient. They reduce repetitive code and improve readability significantly.
Destructuring
Destructuring is a way to unpack values from arrays or properties from objects into individual variables in a single, concise statement.
Array Destructuring
Values are extracted from an array based on their position.
let colors = ["Red", "Green", "Blue"];
// Without destructuring
let first = colors[0];
let second = colors[1];
// With destructuring — much cleaner
let [first, second, third] = colors;
console.log(first); // Red
console.log(second); // Green
console.log(third); // BlueSkipping Elements
let scores = [90, 75, 88, 60, 95];
let [top, , third] = scores;
console.log(top); // 90
console.log(third); // 88 (second item skipped with empty comma)Default Values in Array Destructuring
let data = ["Ajay"];
let [name, age = 18] = data;
console.log(name); // Ajay
console.log(age); // 18 (default — not in array)Swapping Variables with Destructuring
let a = 10, b = 20;
[a, b] = [b, a];
console.log(a); // 20
console.log(b); // 10Object Destructuring
Properties are extracted from an object by matching their key names.
let person = {
name: "Rina",
age: 26,
city: "Kolkata"
};
let { name, age, city } = person;
console.log(name); // Rina
console.log(age); // 26
console.log(city); // KolkataRenaming Variables During Object Destructuring
let product = {
title: "Keyboard",
cost: 1200
};
let { title: productName, cost: price } = product;
console.log(productName); // Keyboard
console.log(price); // 1200Default Values in Object Destructuring
let user = { username: "ravi123" };
let { username, role = "viewer" } = user;
console.log(username); // ravi123
console.log(role); // viewer (default applied)Nested Object Destructuring
let order = {
id: 201,
customer: {
name: "Pallavi",
phone: "9876543210"
}
};
let { id, customer: { name, phone } } = order;
console.log(id); // 201
console.log(name); // Pallavi
console.log(phone); // 9876543210Destructuring in Function Parameters
// Instead of accessing properties manually inside the function
function displayUser({ name, age, city = "Unknown" }) {
console.log(`${name} is ${age} years old from ${city}.`);
}
displayUser({ name: "Kiran", age: 30, city: "Mumbai" });
// Kiran is 30 years old from Mumbai.
displayUser({ name: "Meera", age: 22 });
// Meera is 22 years old from Unknown.Spread Operator ( ... )
The spread operator ... expands an array or object into individual elements. It "spreads" the contents out.
Spread with Arrays
let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];
// Combine arrays
let combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Add elements at any position
let extended = [0, ...arr1, 3.5, ...arr2, 7];
console.log(extended); // [0, 1, 2, 3, 3.5, 4, 5, 6, 7]Copy an Array Without Reference
let original = [10, 20, 30];
let copy = [...original];
copy.push(40);
console.log(original); // [10, 20, 30] — unchanged!
console.log(copy); // [10, 20, 30, 40]Spread with Strings
let letters = [..."Hello"];
console.log(letters); // ["H", "e", "l", "l", "o"]Spread with Math Functions
let numbers = [30, 10, 50, 20, 40];
console.log(Math.max(...numbers)); // 50
console.log(Math.min(...numbers)); // 10Spread with Objects
let defaultSettings = { theme: "light", fontSize: 14 };
let userSettings = { fontSize: 18, language: "Hindi" };
// Merge objects (user settings override defaults)
let finalSettings = { ...defaultSettings, ...userSettings };
console.log(finalSettings);
// { theme: "light", fontSize: 18, language: "Hindi" }Copy an Object
let employee = { name: "Vikram", dept: "Tech" };
let clone = { ...employee, location: "Pune" };
console.log(clone);
// { name: "Vikram", dept: "Tech", location: "Pune" }Rest Parameters ( ... )
The rest parameter ... looks the same as spread but does the opposite — it collects multiple values into a single array. It is used in function parameter lists.
Gathering Remaining Arguments
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
console.log(sum(5)); // 5Rest with Named Parameters
function logUser(name, age, ...hobbies) {
console.log(`Name: ${name}`);
console.log(`Age: ${age}`);
console.log(`Hobbies: ${hobbies.join(", ")}`);
}
logUser("Sania", 25, "Reading", "Painting", "Cycling");
// Name: Sania
// Age: 25
// Hobbies: Reading, Painting, CyclingThe rest parameter must always be the last parameter in the function definition.
Spread vs Rest — The Difference
| Feature | Spread (...) | Rest (...) |
|---|---|---|
| Where used | In function calls, array/object literals | In function parameter definitions |
| What it does | Expands an iterable into individual elements | Collects individual arguments into an array |
| Example | Math.max(...nums) | function fn(...args) |
Practical Example — Shopping Cart
let cart = {
customer: "Anita",
items: ["Bag", "Shoes"]
};
// Add more items using spread
let updatedCart = {
...cart,
items: [...cart.items, "Watch", "Belt"],
totalItems: cart.items.length + 2
};
console.log(updatedCart);
// {
// customer: "Anita",
// items: ["Bag", "Shoes", "Watch", "Belt"],
// totalItems: 4
// }Key Points to Remember
- Destructuring extracts values from arrays or objects into separate variables
- Array destructuring uses position; object destructuring uses property names
- Default values can be set during destructuring in case values are missing
- The spread operator
...expands arrays and objects — great for copying and merging - The rest parameter
...collects remaining function arguments into an array - Spread is used in function calls and literals; rest is used in function definitions
- The rest parameter must always be the last parameter in a function
