Destructuring in JavaScript
Source: Dev.to
🧠 What Is Destructuring?
Unpack values from arrays or objects into distinct variables in a single step.
🔹 Destructuring Arrays
Before
const numbers = [10, 20, 30];
const first = numbers[0];
const second = numbers[1];After
const [first, second, third] = [10, 20, 30];
console.log(first); // 10
console.log(second); // 20
console.log(third); // 30✅ Notes
- Order matters in arrays.
- You can skip items with commas:
const [, , third] = [10, 20, 30];
console.log(third); // 30🔹 Destructuring Objects
Before
const person = { name: "Rahul", age: 22, city: "Delhi" };
const name = person.name;
const age = person.age;After
const { name, age } = { name: "Rahul", age: 22, city: "Delhi" };
console.log(name); // Rahul
console.log(age); // 22- Order does not matter.
- Variable names must match property names (or be renamed).
// Renaming
const { name: userName } = { name: "Rahul" };
console.log(userName); // Rahul🔹 Default Values
If a property might be missing, you can provide a default:
const { name, city = "Unknown" } = { name: "Rahul" };
console.log(city); // UnknownNested Destructuring
const user = { name: "Rahul", address: { city: "Delhi" } };
const { name, address: { city } } = user;
console.log(name); // Rahul
console.log(city); // Delhi⚡ Benefits of Destructuring
- Less repetitive code
- Cleaner and more readable
- Easier to extract nested data
- Works well with function parameters
🔹 Destructuring in Function Parameters
function greet({ name, city = "Unknown" }) {
console.log(`Hello ${name} from ${city}`);
}
greet({ name: "Rahul" });
// Hello Rahul from UnknownBefore
function greet(person) {
const name = person.name;
const city = person.city || "Unknown";
console.log(`Hello ${name} from ${city}`);
}After
function greet({ name, city = "Unknown" }) {
console.log(`Hello ${name} from ${city}`);
}✅ Cleaner, shorter, easier to read.
- Destructuring extracts values from arrays or objects.
- Arrays → order matters.
- Objects → variable names must match keys (or be renamed).
- Supports defaults and nested structures.
- Ideal for cleaner code and function parameters.