🧩 1. What Is Destructuring?
Destructuring means “unpacking” values from arrays or properties from objects into distinct variables.
Instead of doing this:
const user = { name: "Alice", age: 25 };
const name = user.name;
const age = user.age;
You can write:
const { name, age } = user;
✅ Same result, cleaner syntax.
🧮 2. Array Destructuring
🔹 Basic Example
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
You can name the variables anything — they follow position, not key.
🔹 Skipping Elements
You can skip unwanted items with commas:
const numbers = [10, 20, 30, 40];
const [a, , b] = numbers;
console.log(a); // 10
console.log(b); // 30
🔹 Default Values
If a value doesn’t exist, you can assign a default.
const [x = 1, y = 2, z = 3] = [10, 20];
console.log(x, y, z); // 10 20 3
🔹 Swapping Variables
A neat trick using array destructuring:
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10, 5
✅ Clean way to swap values without a temporary variable.
🔹 Nested Arrays
const nested = [1, [2, 3]];
const [one, [two, three]] = nested;
console.log(two); // 2
console.log(three); // 3
🔹 Rest with Arrays
You can gather remaining elements using the rest operator (...
):
const [first, ...others] = [1, 2, 3, 4];
console.log(first); // 1
console.log(others); // [2, 3, 4]
🧱 3. Object Destructuring
🔹 Basic Example
const person = { name: "Bob", age: 30 };
const { name, age } = person;
console.log(name); // "Bob"
console.log(age); // 30
✅ The variable names must match the object’s property names.
🔹 Renaming Variables
You can rename during destructuring:
const user = { id: 101, username: "john_doe" };
const { username: userName } = user;
console.log(userName); // "john_doe"
✅ This is useful to avoid naming conflicts or for readability.
🔹 Default Values
If the property doesn’t exist, use a default:
const user = { name: "Alice" };
const { name, age = 18 } = user;
console.log(name, age); // "Alice", 18
🔹 Nested Objects
You can destructure deep inside objects:
const user = {
name: "Sarah",
address: {
city: "Paris",
zip: 75000,
},
};
const { address: { city, zip } } = user;
console.log(city); // "Paris"
⚠️ Note: address
itself is not declared here — only city
and zip
.
🔹 Using Rest in Objects
You can collect remaining properties:
const user = { name: "John", age: 25, country: "USA" };
const { name, ...details } = user;
console.log(name); // "John"
console.log(details); // { age: 25, country: "USA" }
⚙️ 4. Destructuring in Function Parameters
Destructuring can make function parameters much cleaner.
🧩 Example 1 — Object
function greet({ name, age }) {
console.log(`Hello ${name}, you are ${age} years old.`);
}
const person = { name: "Alice", age: 25 };
greet(person);
// Hello Alice, you are 25 years old.
🧩 Example 2 — Array
function printCoords([x, y]) {
console.log(`X: ${x}, Y: ${y}`);
}
printCoords([10, 20]);
// X: 10, Y: 20
🔁 5. Combining with Default + Nested + Rest
You can mix all these features:
const user = {
name: "Emma",
details: {
city: "Berlin",
},
};
const {
name = "Guest",
details: { city = "Unknown" } = {},
country = "Germany",
} = user;
console.log(name, city, country); // Emma Berlin Germany
🧠 6. Array vs Object Destructuring
Feature | Array | Object |
---|---|---|
Access by | Position | Key name |
Syntax | [a, b] = arr | {x, y} = obj |
Skip values | Yes (use commas) | No |
Default values | Yes | Yes |
Rest operator | const [a, ...b] | const {x, ...y} |
💡 7. Real-World Use Cases
✅ React / Frontend frameworks:
const [count, setCount] = useState(0);
✅ API responses:
const { user, token } = await fetchData();
✅ Config handling:
const { host = "localhost", port = 8080 } = config;
✅ Clean function parameters:
function display({ name, email }) {
console.log(`${name} - ${email}`);
}
🧭 8. Quick Summary
Concept | Example | Description |
---|---|---|
Array destructuring | const [a, b] = arr; | Extract by position |
Object destructuring | const {x, y} = obj; | Extract by property name |
Default values | const [a = 1] = [] | Use fallback values |
Renaming | const {x: newX} = obj | Change variable name |
Rest | const [a, ...rest] = arr | Collect remaining values |
Nested | const {info: {age}} = obj | Access deeply nested values |