Module 14 : Destructuring Objects and Arrays
Destructuring is a powerful feature introduced in ES6 that allows you to unpack values from arrays or properties from objects into distinct variables in a clean and concise way.
๐ Part 1: Destructuring Arrays
✅ Syntax
javascript
code
const [first, second] = [10, 20]; console.log(first); // 10 console.log(second); // 20
✅ Skipping Elements
javascript
code
const [a, , c] = [1, 2, 3]; console.log(a); // 1 console.log(c); // 3
✅ Default Values
javascript
code
const [x = 5, y = 10] = [1]; console.log(x); // 1 console.log(y); // 10
✅ Swapping Variables
javascript
code
let a = 1, b = 2; [a, b] = [b, a]; console.log(a, b); // 2, 1
✅ Rest Operator
javascript
code
const [first, ...rest] = [1, 2, 3, 4]; console.log(rest); // [2, 3, 4]
๐ Part 2: Destructuring Objects
✅ Syntax
javascript
code
const user = { name: 'Alice', age: 30 }; const { name, age } = user; console.log(name); // Alice
✅ Renaming Variables
javascript
code
const { name: userName, age: userAge } = user; console.log(userName); // Alice
✅ Default Values
javascript
code
const { role = 'guest' } = {}; console.log(role); // guest
✅ Nested Destructuring
javascript
code
const person = { name: 'John', address: { city: 'Mumbai', zip: 400001 } }; const { address: { city } } = person; console.log(city); // Mumbai
✅ Rest Operator in Objects
javascript
code
const { name, ...others } = { name: 'Tom', age: 40, role: 'Admin' }; console.log(others); // { age: 40, role: 'Admin' }
Examples
1. API Response Destructuring
javascript
code
const response = { status: 200, data: { user: { id: 1, name: 'Reha' }, token: 'abc123' } }; const { data: { user: { name }, token } } = response; console.log(name); // Rehana console.log(token); // abc123
2. Function Parameter Destructuring
javascript
code
function greet({ name, age }) { return `Hello ${name}, age ${age}`; } console.log(greet({ name: 'Sara', age: 28 }));
๐งช Exercises (With Solutions)
✅ Exercise 1: Destructure this array
javascript
code
// Given const fruits = ['Apple', 'Banana', 'Mango']; // Task: Extract first and third elements into variables
✅ Solution:
javascript
code
const [first, , third] = fruits; console.log(first, third); // Apple Mango
✅ Exercise 2: Destructure object with renaming and default
javascript
code
// Given const car = { brand: 'Toyota', year: 2022 }; // Task: Destructure brand as carBrand, set default value for color
✅ Solution:
javascript
code
const { brand: carBrand, color = 'Red' } = car; console.log(carBrand, color); // Toyota Red
✅ Exercise 3: Nested destructuring
javascript
code
// Given const student = { name: 'Ahmed', scores: { math: 90, science: 85 } }; // Task: Extract math and science scores
✅ Solution:
javascript
code
const { scores: { math, science } } = student; console.log(math, science); // 90, 85
๐ Notes
Start with a visual analogy: Use a gift box (array) and a label (variable) analogy to demonstrate unpacking values.
Show side-by-side before and after code to emphasize how destructuring simplifies code.
Use browser dev tools or CodePen to live-code examples interactively.
Highlight pitfalls such as undefined values when destructuring non-existing keys.
Compare destructuring with traditional assignment to show improvements.
๐ Advanced Insights
๐ Performance:
Destructuring has negligible performance impact, but it's not meant for performance gains—it's about code clarity and cleaner syntax.
๐ Usage in Frameworks:
React: Destructuring props and hooks is common.
javascript
code
function Welcome({ name }) { return <h1>Hello, {name}</h1>; }
Node.js: Modules use destructuring for importing specific features.
javascript
code
const { readFileSync } = require('fs');
๐ Compatibility:
Supported in ES6+, so it’s widely available in all modern browsers.
Use transpilers (like Babel) when targeting old browsers (e.g., IE11).
๐ง Summary
Feature
Array
Object
Basic Syntax
✅
✅
Skipping
✅
❌
Default Values
✅
✅
Renaming
❌
✅
Nested
✅
✅
Rest
✅
✅
Destructuring improves code readability, reduces boilerplate, and is foundational for modern JavaScript development.
Checklist
✅ Understand array and object destructuring
✅ Use destructuring in functions
✅ Handle nested and rest patterns
✅ Apply destructuring in use cases
✅ Teach with practical analogies and exercises
No comments:
Post a Comment