Hey Devs ๐
Today, letโs talk about Object Spread (...
) and Rest (...
) in JavaScript โ two powerful features that often confuse beginners. Iโll keep it simple with examples and a clear takeaway at the end. ๐
๐น Object Spread
Spread is used to copy, merge, or override properties of objects.
Example 1 โ Merge Objects
const birdDetails = {
name: "Crow",
color: "black",
};
const birdHabitat = {
region: "South Africa",
climate: "warm to hot",
};
const parrotInfo = {
...birdDetails,
...birdHabitat,
};
console.log(parrotInfo);
// { name: "Crow", color: "black", region: "South Africa", climate: "warm to hot" }
Here, both objects are combined into a new object parrotInfo
.
Example 2 โ Override Properties
const car = {
brand: "Toyota",
name: "Toyota Corolla",
color: "white",
};
const newCar = {
...car,
speed: "220km/h",
brand: "Honda",
name: "Honda Civic",
};
console.log(newCar);
// { brand: "Honda", name: "Honda Civic", color: "white", speed: "220km/h" }
Notice how brand
and name
got overwritten after spreading.
๐น Object Rest
Rest is used to extract the remaining properties of an object after destructuring some.
Example 1 โ Direct Destructuring
const student = {
name: "Usama",
age: 22,
grade: "4.5",
city: "Karachi",
};
const { name, age, ...another } = student;
console.log("Directly Remaining properties:", another);
console.log("Directly Name and Age:", name, age);
// Directly Remaining properties: { grade: "4.5", city: "Karachi" }
// Directly Name and Age: Usama 22
Example 2 โ Inside a Function
function remaProp({ name, age, ...another }) {
console.log("Remaining properties:", another);
console.log("Name and Age:", name, age);
}
remaProp(student);
// Remaining properties: { grade: "4.5", city: "Karachi" }
// Name and Age: Usama 22
โจ Summary
-
Spread (
...
) โ Copy, merge, or override object properties. -
Rest (
...
) โ Collect leftover properties after extracting specific ones.
๐ฅ With these two in your toolkit, working with objects in JS becomes much easier!
๐ก Whatโs your favorite use case of spread/rest in JavaScript? Drop it in the comments ๐
Top comments (0)