Object Destructuring in JavaScript

📌 What is Object Destructuring?

Object destructuring is a convenient syntax in JavaScript that allows you to extract properties from objects and assign them to variables in a concise way. It makes your code cleaner and easier to read. ✂️📦

🔤 Basic Syntax

Basic Object Destructuring

const person = {
  name: "Alice",
  age: 30,
  city: "New York"
};

const { name, age } = person;

console.log(name); // Alice
console.log(age);  // 30

💡 Assigning to New Variable Names

You can rename variables while destructuring:

Destructure with New Variable Names

const { name: userName, city: userCity } = person;

console.log(userName); // Alice
console.log(userCity); // New York

⚙️ Default Values

If a property does not exist in the object, you can assign a default value:

Destructure with Default Values

const { name, country = "USA" } = person;

console.log(country); // USA

🧱 Nested Object Destructuring

You can destructure nested objects easily:

Nested Destructuring

const user = {
  id: 101,
  name: "Bob",
  address: {
    street: "123 Main St",
    city: "Boston"
  }
};

const { address: { city } } = user;

console.log(city); // Boston

🚫 Beware: Destructuring Undefined or Null

Trying to destructure from undefined or null causes an error. Make sure the object exists or use default parameters.

🧠 Using Destructuring in Function Parameters

Destructuring can be used directly in function parameters for cleaner code:

Function Parameter Destructuring

function greet({ name, age }) {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet(person); // Hello, Alice! You are 30 years old.

📚 Summary

  • Extract object properties into variables concisely.
  • Supports renaming variables and default values.
  • Works with nested objects for deep extraction.
  • Useful in function parameters for clean APIs.

📖 Learn More

>>“Destructuring helps you write less code and express your intent clearly.” ✂️✨