Skip to content

Commit d3cad8d

Browse files
Update optional-chaining.md
1 parent f557988 commit d3cad8d

File tree

1 file changed

+52
-32
lines changed

1 file changed

+52
-32
lines changed

content/javascript/concepts/optional-chaining/optional-chaining.md

Lines changed: 52 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ CatalogContent:
1414

1515
The **optional chaining** operator simplifies comparing multiple data properties in a chain of connected objects. This is especially valuable if any of the properties are `null`, as the operator will return `undefined` instead of throwing an error.
1616

17-
Optional chaning can be used to validate nested object properties, call optional functions or methods on optional objects, accessing arrary elements, and more.
17+
Optional chaning can be used to validate nested object properties, call optional functions or methods on optional objects, accessing array elements, and more.
1818

1919
The primary benefits of using optional chaining instead of regular syntax include simplifying the code to achieve the same result, making it easier to read, protecting against runtime errors, and enhancing maintainability.
2020

@@ -33,8 +33,10 @@ array?.[index]
3333
object?.method?.()
3434
```
3535
36-
## Example
37-
This person object lists an individual's details and containing properties, nested objects, an array, and a method. Optional chaining for each conditional evaluation is listed below.
36+
## Examples
37+
38+
### Accessing Object Properties
39+
To search for the `state` object of `person`:
3840
3941
```js
4042
const person = {
@@ -44,48 +46,66 @@ const person = {
4446
address: {
4547
street: "1111 Palm Ave",
4648
city: "Broken Arrow",
47-
state: "Oklahoma"
49+
state1: "Oklahoma"
4850
},
4951
favoriteFoods: ["pizza", "ice cream", "cake"],
5052
commonPhrase: function() {
51-
return `${this.name} always says "I love ${this.address.state}."`;
53+
return `${this.name} always says "I love ${this.address.state1}."`;
5254
}
5355
};
54-
```
5556

56-
## Accessing Object Properties
57-
To search for the `state` object of `person`:
57+
// Regular syntax for checking if the state1 property exists
58+
const state1Regular = person && person.address && person.address.state1;
59+
console.log(`State (regular syntax) is: ${state1Regular}`);
5860

59-
```js
60-
//Regular syntax
61-
const state = person && person.address && person.address.state;
62-
console.log(`State is: ${state}`);
61+
// This can be rewritten as:
62+
const state1Chaining = person?.address?.state1;
63+
console.log(`State (optional chaining) is: ${state1Chaining}`);
64+
```
6365
64-
//This can be rewritten as:
65-
const state = person?.address?.state;
66-
console.log(`State is: ${state}`);
66+
The output of the above code will be as follows:
6767
68-
//The output for both is:
69-
State is: Oklahoma
68+
```shell
69+
State (regular syntax) is: Oklahoma
70+
State (optional chaining) is: Oklahoma
7071
```
7172
72-
## Accessing Arrary Elements
73+
### Accessing Array Elements
7374
To search for the `cake` in the `favoriteFoods` array of `person`:
7475
7576
```js
76-
//Regular Syntax
77-
const food = person && person.favoriteFoods && person.favoriteFoods.find(item => item === "cake");
78-
console.log(`Favorite Food is: ${food}`);
77+
const person = {
78+
name: "Alice",
79+
gender: "Female",
80+
age: 12,
81+
address: {
82+
street: "1111 Palm Ave",
83+
city: "Broken Arrow",
84+
state1: "Oklahoma"
85+
},
86+
favoriteFoods: ["pizza", "ice cream", "cake"],
87+
commonPhrase: function() {
88+
return `${this.name} always says "I love ${this.address.state1}."`;
89+
}
90+
};
7991

80-
//This can be rewritten as:
81-
const food = person?.favoriteFoods.find(item => item === "cake");
82-
console.log(`Favorite Food is: ${food}`)
92+
// Regular Syntax for searching favorite food
93+
const foodRegular = person && person.favoriteFoods && person.favoriteFoods.find(item => item === "cake");
94+
console.log(`Favorite Food (regular syntax) is: ${foodRegular}`);
8395

84-
//The output for both is:
85-
Favorite Food is: cake
96+
// This can be rewritten as:
97+
const foodChaining = person?.favoriteFoods.find(item => item === "cake");
98+
console.log(`Favorite Food (optional chaining) is: ${foodChaining}`);
99+
```
100+
101+
The output of the above code will be as follows:
102+
103+
```shell
104+
Favorite Food (regular syntax) is: cake
105+
Favorite Food (optional chaining) is: cake
86106
```
87107
88-
## Accessing Object Functions
108+
### Accessing Object Functions
89109
To determine if the `commonPhrase` function exists in `person` before invoking it:
90110
91111
```js
@@ -153,15 +173,15 @@ const people = [
153173
}
154174
];
155175

156-
// Regular syntax for checking if a person's city exists
176+
console.log("Using Regular Syntax for City:");
157177
people.forEach((person, index) => {
158178
const city = person && person.address && person.address.city;
159-
console.log(`Person ${index + 1}: City: ${city}`);
179+
console.log(`Person ${index + 1}: City: ${city ?? "Not Available"}`);
160180
});
161181
162-
// Optional chaining for simpler access
182+
console.log("\nUsing Optional Chaining for Age:");
163183
people.forEach((person, index) => {
164-
const age = person?.age;
165-
console.log(`Person ${index + 1}: Age: ${age}`);
184+
const age = person?.age;
185+
console.log(`Person ${index + 1}: Age: ${age ?? "Not Available"}`);
166186
});
167187
```

0 commit comments

Comments
 (0)