mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-04-12 10:00:39 -04:00
feat(curriculum): Add interactive examples to What Is the Optional Chaining Operator, and How Does It Work (#63331)
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user