Destructuring assignment (introduced in ES6) provides a concise syntax to unpack values from arrays or properties from objects directly into distinct variables.
flowchart TD
Destruct["Destructuring Syntax"] --> ObjDest["Object Destructuring: const { name, age = 18 } = user;"]
Destruct --> ArrDest["Array Destructuring: const [first, second, ...rest] = list;"]
| Pattern | Code Example | Explanation |
|---|---|---|
| Object Property Renaming | const { a: newA } = obj; |
Binds property a to local variable newA. |
| Default Fallback Values | const { role = "guest" } = obj; |
Uses "guest" if property is undefined. |
| Array Skipping | const [a, , c] = array; |
Skips second element using empty comma slot. |
| Rest Gathering | const [head, ...tail] = list; |
Gathers remaining elements into tail array. |
| Function Parameter Unpacking | function show({ id, title }) {} |
Unpacks target properties directly in function parameter list. |
// Demonstrating Object, Array, and Function Parameter Destructuring
// 1. Object Destructuring with Renaming and Defaults
const developer = {
id: 101,
username: "maksudur_dev",
details: { email: "[email protected]", location: "Dhaka" }
};
const {
username: handle, // Rename username to handle
details: { email }, // Nested object destructuring
status = "Active" // Default fallback value
} = developer;
console.log(`Handle: ${handle}, Email: ${email}, Status: ${status}`);
// 2. Array Destructuring with Rest Gathering
const coordinates = [23.8103, 90.4125, 10.5]; // [Lat, Lng, Elevation]
const [latitude, longitude, elevation = 0] = coordinates;
console.log(`Lat: ${latitude}, Lng: ${longitude}, Elev: ${elevation}`);
// 3. Swapping Variables without Temporary Variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(`Swapped: x=${x}, y=${y}`); // x=2, y=1
// 4. Function Parameter Destructuring
function renderUserProfile({ id, username }) {
console.log(`Rendering Card for #${id}: ${username}`);
}
renderUserProfile(developer);
null or undefined Throws TypeError: const { x } = null; throws TypeError: Cannot destructure property of null. Provide default empty objects ({ x } = obj || {}).function configure({ host = "localhost", port = 8080 } = {}) so the function can be called with zero arguments configure().const { a: { b: { c: { d } } } } = data), as it degrades readability.Unpack the first and third items of const colors = ["red", "green", "blue"] into variables primary and tertiary.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.