JavaScript Notes
Master JavaScript object destructuring: rename variables, default values, nested destructuring, function parameter destructuring, and array destructuring with real-world examples.
What is Destructuring?
Destructuring is a JavaScript syntax that lets you unpack values from objects (or arrays) into individual variables in a single line. Instead of writing user.name, user.age, user.city three times, destructuring pulls them all out at once.
Think of it like unpacking a suitcase: instead of reaching into the suitcase every time you need something, you lay everything out on the table at the start.
Basic Object Destructuring
const student = {
name: "Priya",
marks: 92,
grade: "A",
city: "Bangalore"
};
const { name, marks, grade } = student;
console.log(name);
console.log(marks);
console.log(grade);Priya 92 A
Renaming Variables While Destructuring
When you want a different variable name than the object key:
const apiResponse = {
user_name: "rahul_dev",
user_age: 28,
user_email: "rahul@example.com"
};
// Syntax: { originalKey: newVariableName }
const { user_name: username, user_age: age, user_email: email } = apiResponse;
console.log(username);
console.log(age);
console.log(email);rahul_dev 28 rahul@example.com
Default Values in Destructuring
If a key doesn't exist in the object, use = to provide a fallback:
const config = { theme: "dark", language: "en" };
const { theme, language, fontSize = 16, notifications = true } = config;
console.log(theme); // from object
console.log(language); // from object
console.log(fontSize); // default (key missing)
console.log(notifications); // default (key missing)dark en 16 true
Rename + Default Value Together
const settings = { maxItems: 50 };
const {
maxItems: limit = 100, // rename AND provide default
timeout: delay = 3000 // key missing → uses default 3000
} = settings;
console.log(limit); // 50 (from object)
console.log(delay); // 3000 (default)50 3000
Nested Object Destructuring
const employee = {
name: "Aman",
department: "Engineering",
address: {
city: "Hyderabad",
pincode: 500001,
country: "India"
}
};
// Destructure nested address
const {
name,
address: { city, pincode } // nested destructuring
} = employee;
console.log(name);
console.log(city);
console.log(pincode);Aman Hyderabad 500001
⚠️ Note:addressis not created as a variable here — onlycityandpincodeare extracted.
Destructuring in Function Parameters
This is one of the most powerful real-world uses:
// ❌ Without destructuring — verbose
function displayUser(user) {
console.log(`${user.name} (${user.age}) from ${user.city}`);
}
// ✅ With destructuring in parameters
function displayUser({ name, age, city }) {
console.log(`${name} (${age}) from ${city}`);
}
const user = { name: "Neha", age: 25, city: "Pune", role: "dev" };
displayUser(user);Neha (25) from Pune
With default parameter values
function createProfile({ name, role = "member", verified = false } = {}) {
return { name, role, verified };
}
console.log(createProfile({ name: "Tara" }));
console.log(createProfile({ name: "Admin", role: "admin", verified: true }));{ name: 'Tara', role: 'member', verified: false }
{ name: 'Admin', role: 'admin', verified: true }Destructuring in for...of Loops
[1] Phone - ₹15000 [2] Laptop - ₹55000 [3] Tablet - ₹25000
Destructuring with Rest Operator
const { name, role, ...otherInfo } = {
name: "Ravi",
role: "admin",
age: 30,
city: "Chennai",
company: "TechX"
};
console.log(name);
console.log(role);
console.log(otherInfo);Ravi
admin
{ age: 30, city: 'Chennai', company: 'TechX' }Array Destructuring
10 20 30 1 3 5 200 100
Destructuring Function Return Values
Min: 62, Max: 95, Avg: 79.6
Real World Use Cases 🌍
| Use Case | Example |
|---|---|
| API response unpacking | const { data, status, message } = apiResponse |
| React props | function Button({ label, onClick, disabled = false }) |
| Configuration options | const { port = 3000, host = "localhost" } = options |
| Multiple return values | const { success, data, error } = fetchData() |
| Rename snake_case to camelCase | const { first_name: firstName } = response |
Common Mistakes ❌
1. Destructuring from null/undefined
2. Forgetting nested structure creates no middle variable
const user = { address: { city: "Jaipur" } };
const { address: { city } } = user;
console.log(city); // "Jaipur" ✅
// console.log(address); // ❌ ReferenceError — 'address' not created as variable
// ✅ To get both:
const { address, address: { city: userCity } } = user;3. Default value only kicks in for undefined, NOT null
// ❌ Misconception
const { score = 100 } = { score: null };
console.log(score); // null — NOT 100!
// Default only applies if value is undefined:
const { score: s = 100 } = { score: undefined };
console.log(s); // 100 ✅Interview Questions 🎯
Q1. What is destructuring in JavaScript? > A syntax that allows extracting values from objects or arrays into variables in a single statement. Introduced in ES6 (ES2015).
Q2. How do you rename a variable during destructuring? > const { originalKey: newName } = obj — the colon syntax renames it.
Q3. How do you provide a default value in destructuring? > const { key = defaultValue } = obj — the = provides a fallback if the key is undefined.
Q4. What is nested destructuring? > Extracting properties from objects nested inside other objects: const { outer: { inner } } = obj.
Q5. When does a default value in destructuring apply? > Only when the property value is undefined. A null value does not trigger the default.
Q6. How is destructuring useful in function parameters? > It allows you to name the exact properties you need from an object argument, improving readability and avoiding obj.key repetition.
Q7. What's the difference between array and object destructuring? > Object destructuring uses {} and extracts by key name. Array destructuring uses [] and extracts by position. You can combine both.
Q8. How do you destructure with rest in objects? > const { a, b, ...rest } = obj — a and b are extracted, everything else goes into rest.
Key Takeaways 🏁
- Destructuring extracts object properties into standalone variables in one line
- Use
:to rename variables:{ key: newName } - Use
=to set defaults:{ key = value } - Nested destructuring:
{ outer: { inner } }— middle key is NOT a variable - Defaults only activate for
undefined, notnull - Function parameters benefit most from destructuring — eliminates
props.xrepetition - Combine with rest
...to collect remaining properties
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Object Destructuring - Complete Guide with Examples.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, objects, destructuring, javascript object destructuring - complete guide with examples
Related JavaScript Master Course Topics