Destructuring & defaults
Unpack the values you need
Lesson 13 of 20 · 10 min · Module 5: Reliable data pipelines
A record often carries more information than one function needs. Destructuring gives the useful parts local names and makes sensible defaults visible.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Read object properties with destructuring
- Apply defaults only to undefined values
The idea
Use const { title = "Untitled", minutes = 0 } = session to read two properties. A default applies when a property is missing or undefined, rather than replacing every falsy value.
const { name = "Guest", streak = 0 } = { name: "Alex" };
console.log(name, streak);
01Read the shape before the values
The property names on the left describe what you want to extract. The object on the right supplies those values. You can ignore unrelated properties.
02Keep zero meaningful
A duration of zero is still a supplied number. A destructuring default preserves it. Using minutes || 10 would replace zero, because zero is falsy.
const { minutes = 10 } = { minutes: 0 };
console.log(minutes);003Trace a missing property
For an empty object, neither property exists. The two defaults produce the complete label without changing the input object.
Your turn
sessionLabel(session). Read title and minutes with defaults "Untitled" and 0, and return "Loops · 12 min" for {title:"Loops", minutes:12}. Preserve an explicitly empty title and zero minutes. Inputs are objects.What the checks look for
- Uses the values supplied by the caller
- Defaults both missing properties
- Keeps explicit empty and zero values
Take this with you
A clear input shape makes a function easier to read and use.
Go a little further
Add a difficulty property with a default, while keeping the original object unchanged.