DEV Community

Cover image for ✨ Mastering Object Spread & Rest in JavaScript
Usama
Usama

Posted on

✨ Mastering Object Spread & Rest in JavaScript

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" }
Enter fullscreen mode Exit fullscreen mode

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" }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

✨ 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)