DEV Community

Usama
Usama

Posted on

Mastering Object Mastering Object Destructuring in JavaScript ✨

Object Destructuring is one of the most powerful and readable features in JavaScript. It allows you to extract values from objects and assign them to variables in a clean, concise way.


1. Basic Destructuring 🐦

const car = {
  brand: "BYD",
  model: "ATTO 2",
};

const { brand, model } = car;

console.log(brand); // BYD
console.log(model); // ATTO 2
Enter fullscreen mode Exit fullscreen mode

This extracts properties directly into variables.


2. Renaming Variables ✍️

You can rename while destructuring:

const { brand: carBrand } = car;

console.log(carBrand); // BYD
Enter fullscreen mode Exit fullscreen mode

3. Nested Destructuring 🌳

Objects inside objects? No problem:

const bird = {
  name: "house sparrow",
  length: "6.3in",
  mass: "39g",
  coloured: {
    male: "white/brown",
    female: "brown/grey",
  },
  canFly: true,
};
Enter fullscreen mode Exit fullscreen mode
const {
  coloured: { female: femaleColor },
} = bird;

console.log(femaleColor); // brown/grey
Enter fullscreen mode Exit fullscreen mode

4. Combining Properties 🛠️

Extract multiple properties at once:

const {
  name,
  mass,
  coloured: { male, female },
  canFly,
} = bird;

console.log(name);   // house sparrow
console.log(mass);   // 39g
console.log(male);   // white/brown
console.log(female); // brown/grey
console.log(canFly); // true
Enter fullscreen mode Exit fullscreen mode

5. Default Values ✅

If a property doesn’t exist, you can set a default:

const { wingspan = "unknown" } = bird;
console.log(wingspan); // unknown
Enter fullscreen mode Exit fullscreen mode

🚀 Why Destructuring Matters

  • Makes code cleaner and shorter.
  • Easier to read and maintain.
  • Useful in React props, API responses, and config objects.

Final Thoughts 💡

Object destructuring is not just “syntax sugar”—it’s a tool that makes your JavaScript code more elegant and professional. Start small, practice with nested objects, and you’ll soon use it everywhere in your codebase.


✍️ Thanks for reading! If you found this helpful, don’t forget to leave a ❤️ on Dev.to and share it with other developers.

MY GITHUB Repo 🦊:

https://github.com/Usamaazeem03/javaScript-a-to-z-concept.git

Top comments (0)