Lesson 5
Destructuring
Build a practical mental model for destructuring and use it in working JavaScript.
By the end, you will be able to…
- Explain destructuring in your own words
- Use destructuring in a small program
- Recognize and debug a common failure mode
Build the mental model
Destructuring unpacks values from objects and arrays into named variables in a single statement, optionally supplying defaults for missing properties.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
It removes repetitive user.name, user.role, user.email-style access and makes function parameters self-documenting.
Real-world example
React components destructure props ({ title, onClose }) in almost every function signature you'll write.
Common mistakes
- Misspelling a property name and getting undefined instead of an error
- Forgetting defaults for optional properties that might be missing
- Destructuring deeply nested structures in one unreadable line
Try it yourself
Challenge
Destructure id, title, and a defaulted 'done' flag from the task object.
Knowledge check
What does `const { role = "learner" } = user;` do if user.role is undefined?
Summary
Use destructuring to unpack objects and arrays into clearly named variables, with defaults where useful.