JavaScript course · Part 6: Structure and data · lab 8 of 11
Working with data
Reading values out of objects safely, unpacking and copying with destructuring and spread, the reference bug that catches everyone, and saving data between visits.
By the end you can
- Read nested values without crashing on missing data
- Unpack and copy objects and arrays cleanly
- Explain why changing one array changed another
- Save and load data, and handle the ways that fails
Easier if you did first
step 1 of 4
Reading values that might not be there
Data from a server, a form or another developer is rarely the exact shape you expected. Reading it carelessly is one of the most common ways a page breaks.
You reach into an object with a dot when you know the name: order.guests. You use brackets when the name is in a variable, or is not a plain word: order["guest count"], order[field].
Reading a missing property is not an error. It gives undefined. The error comes one step later, when you read a property of that undefined, which is the Cannot read properties of undefined message from the foundations lab.
?. is the fix. order.customer?.email stops and gives undefined the moment anything in the chain is missing, instead of throwing. It is called optional chaining.
Pair it with ?? for a fallback: order.customer?.email ?? "no email on file". Use ?? rather than ||, for the reason you met earlier: a real 0 or an empty string is a valid value that || would throw away.
Do not reach for ?. everywhere. Use it where data might genuinely be missing. On something you built yourself a line ago it hides a bug rather than preventing one.
Fix the three readings on the right.
order.customer.email throws if customer is missing
order.customer?.email undefined instead
order.customer?.email ?? "-" with a fallback
order["guest count"] brackets for awkward names
order[field] brackets when the name is in a variableWhat these words mean
- dot access
- object.name, when you know the name.
- bracket access
- object[name], when the name is in a variable.
- ?.
- Optional chaining: stop and give undefined rather than throwing.
- ??
- A fallback used only when the value is null or undefined.
- undefined
- What you get for a property that is not there.
Easy to get wrong
data.user.address.city on data from a server
data.user?.address?.city ?? 'Unknown'
One missing level throws, and the whole function stops, often taking the rest of the page's set-up with it. The optional version carries on with a sensible value.
?. on everything, including your own freshly built objects
Only where data can really be missing
It silences the error that would have told you your own code built the wrong shape, so the bug surfaces later and further away.
What we check
- An email that exists comes back
- A missing customer does not throw
- A customer with no email falls back too
- A real zero survives
- Any field can be read by name
- Optional chaining is used
Nothing printed yet. Run your code.