Destructuring
Destructuring lets you extract values from objects and arrays into individual
variables. It's one of the most useful features in modern JavaScript/TypeScript.
Object Destructuring
const user = { name: 'Alice', age: 30, email: 'alice@example.com' }
// Without destructuring
const name = user.name
const age = user.age
// With destructuring
const { name, age } = user
Array Destructuring
const numbers = [1, 2, 3, 4, 5]
// Extract first two elements
const [first, second] = numbers // first = 1, second = 2
// Skip elements
const [, , third] = numbers // third = 3
// Rest pattern
const [head, ...tail] = numbers // head = 1, tail = [2, 3, 4, 5]
Why Use Destructuring?
- Cleaner code - No repetitive
object.propertyaccess - Self-documenting - Variable names show what you're using
- Default values - Provide fallbacks for missing properties
- Function parameters - Extract what you need directly
// Destructuring in function parameters
function greetUser({ name, age }: { name: string; age: number }) {
return `Hello ${name}, you are ${age} years old`
}
Destructuring is everywhere in React. Props destructuring, hook returns like
const [count, setCount] = useState(0), and extracting data from API
responses.In this exercise, you'll master destructuring for objects, arrays, and function
parameters.