Have you ever written code like this?
```js id="before1"
const user = { name: "Rahul", age: 22 };
const name = user.name;
const age = user.age;
It worksβbut itβs **repetitive**.
Destructuring lets you **extract values from arrays or objects in a cleaner way**.
---
## π§ What Is Destructuring?
Destructuring is a JavaScript feature that allows you to:
> Unpack values from arrays or objects into **distinct variables** in a single step.
---
## πΉ Destructuring Arrays
Instead of:
```js id="arrayBefore"
const numbers = [10, 20, 30];
const first = numbers[0];
const second = numbers[1];
Use destructuring:
```js id="arrayAfter"
const [first, second] = [10, 20, 30];
console.log(first); // 10
console.log(second); // 20
### β
Notes:
* Order matters in arrays
* You can skip items with commas:
```js id="arraySkip"
const [ , , third] = [10, 20, 30];
console.log(third); // 30
π Array Destructuring Visual
[10, 20, 30] β first = 10, second = 20, third = 30
πΉ Destructuring Objects
Instead of:
```js id="objBefore"
const user = { name: "Rahul", age: 22, city: "Delhi" };
const name = user.name;
const age = user.age;
Use destructuring:
```js id="objAfter"
const { name, age } = { name: "Rahul", age: 22, city: "Delhi" };
console.log(name); // Rahul
console.log(age); // 22
β Notes:
- Order does not matter
- Variable names must match property names
πΉ Renaming Variables
```js id="rename1"
const { name: userName, age: userAge } = { name: "Rahul", age: 22 };
console.log(userName); // Rahul
console.log(userAge); // 22
---
### πΉ Default Values
If a property might be missing:
```js id="default1"
const { name, city = "Unknown" } = { name: "Rahul" };
console.log(city); // Unknown
π Object Destructuring Visual
{ name: "Rahul", age: 22 } β name = "Rahul", age = 22
πΉ Nested Destructuring
```js id="nested1"
const user = { name: "Rahul", address: { city: "Delhi", zip: 110001 } };
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
```js id="funcParam"
function greet({ name, city = "Unknown" }) {
console.log(`Hello ${name} from ${city}`);
}
greet({ name: "Rahul" });
// Hello Rahul from Unknown
β‘ Before vs After Destructuring
Before:
```js id="before2"
const user = { name: "Rahul", age: 22 };
const name = user.name;
const age = user.age;
**After:**
```js id="after2"
const { name, age } = { name: "Rahul", age: 22 };
β Cleaner, shorter, easier to read
π§ Key Takeaways
- Destructuring extracts values from arrays or objects
- Arrays β order matters
- Objects β variable names must match keys (or rename)
- Supports defaults and nested structures
- Ideal for cleaner code and function parameters
Top comments (0)