Destructuring in JavaScript: Extract Values with Ease

Day 28/50 – JavaScript Interview Question? Question: What is destructuring in JavaScript? Simple Answer: Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. It provides a concise way to extract multiple values in a single statement. 🧠 Why it matters in real projects: Destructuring makes code cleaner and more readable, especially with React props, API responses, and function parameters. It's ubiquitous in modern JavaScript and reduces boilerplate code significantly. 💡 One common mistake: Trying to destructure null or undefined, which throws an error. Always provide default values or check for existence when destructuring data from APIs or external sources. 📌 Bonus: // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const user = { name: 'Alice', age: 30, city: 'NYC' }; const { name, age } = user; console.log(name); // "Alice" // Renaming variables const { name: userName, age: userAge } = user; // Default values (prevents undefined) const { country = 'USA' } = user; console.log(country); // "USA" // Nested destructuring const data = { user: { profile: { email: 'a@b.com' } } }; const { user: { profile: { email } } } = data; // React props destructuring function UserCard({ name, age, onDelete }) { return <div>{name}, {age}</div>; } // Function parameters function displayUser({ name, age = 18 }) { console.log(`${name} is ${age}`); } // Common mistake - destructuring undefined const { x } = null; // ✗ TypeError! const { x } = null || {}; // ✓ Safe with fallback #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ES6 #Destructuring #WebDev #InterviewPrep

To view or add a comment, sign in

Explore content categories