Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 6.2 — Reading and Changing Properties
JavaScript · Example 3 of 4 ES2020+

Optional chaining in a list of users

u.greet?.() calls the method only if it exists. The last block shows what happens without ?.: Ravi has no address, so reading .city of undefined throws.

You read and write properties with a dot (obj.name) or square brackets (obj[key]), add them by assigning, remove them with delete, test for them with in or Object.hasOwn, and read deep values safely with optional chaining ?..

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write getField(obj, field) that returns the value of any field name passed in, or the text "missing" if the object doesn't have that own property. Test it with { a: 1, b: undefined } and the fields a, b and c.

02

Given const order = { customer: { name: "Asha" } }, log the customer's phone number, or "no phone", in one expression without errors. Then do the same for const order2 = {}.

03

Start with const settings = { theme: "dark", debug: true }. Remove debug, add fontSize: 16, and log the result.

Explain it without notes

01

When must you use bracket notation instead of dot notation?

02

What's the difference between in, Object.hasOwn and comparing with undefined?

03

What does optional chaining do, and where is it the wrong tool?

04

Why does obj[{}] usually cause bugs?

Optional chaining in a list of users ES2020+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Asha Pune Pune Hi, I'm Asha
Ravi undefined city unknown undefined
undefined
TypeError: Cannot read properties of undefined (reading 'city')