From bc658f44be282164c19db6ef1d0b8a216e98d5cc Mon Sep 17 00:00:00 2001 From: Clarence Bakosi Date: Fri, 31 Oct 2025 10:18:19 +0100 Subject: [PATCH] feat(curriculum): Add interactive examples to What Is the Optional Chaining Operator, and How Does It Work (#63331) --- .../6732b76c03f7d825c7fc74ee.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/curriculum/challenges/english/blocks/lecture-working-with-optional-chaining-and-object-destructuring/6732b76c03f7d825c7fc74ee.md b/curriculum/challenges/english/blocks/lecture-working-with-optional-chaining-and-object-destructuring/6732b76c03f7d825c7fc74ee.md index 1753f3eb157..07c31dad8e5 100644 --- a/curriculum/challenges/english/blocks/lecture-working-with-optional-chaining-and-object-destructuring/6732b76c03f7d825c7fc74ee.md +++ b/curriculum/challenges/english/blocks/lecture-working-with-optional-chaining-and-object-destructuring/6732b76c03f7d825c7fc74ee.md @@ -5,10 +5,12 @@ challengeType: 19 dashedName: what-is-the-optional-chaining-operator-and-how-does-it-work --- -# --description-- +# --interactive-- The optional chaining operator (`?.`) is a useful tool in JavaScript that lets you safely access object properties or call methods without worrying whether they exist. It's like a safety net for working with objects that might have missing parts. +:::interactive_editor + ```js const person = { name: "Alice", @@ -19,6 +21,8 @@ console.log(person.name); // "Alice" console.log(person.job); // undefined ``` +::: + In this example, `person.name` exists, so it logs `Alice`. But `person.job` doesn't exist, so it gives us `undefined`. Now, let's say we want to access a property of an object that might not exist: @@ -34,7 +38,9 @@ console.log(person.address.street); // This will throw an error! This example will throw an `Uncaught TypeError`. Since `person.address` is `undefined`, we are not able to access the `street` property. This is where the optional chaining operator comes in handy. Here is an example of using the optional chaining operator: -```js +:::interactive_editor + +```ts const user = { name: "John", profile: { @@ -46,10 +52,12 @@ const user = { } }; -console.log(user.profile?.address?.street); // "123 Main St" -console.log(user.profile?.phone?.number); // undefined +console.log(user?.profile?.address?.street); // "123 Main St" +console.log(user?.profile?.phone?.number); // undefined ``` +::: + By using the optional chaining operator, we are telling JavaScript to only continue with the operation if the object (or the value before the `?.`) exists and is not `null` or `undefined`. If the value before the `?.` is `null` or `undefined`, JavaScript returns `undefined` rather than attempting to proceed with the operation and throwing an error.