Skip to content

Commit 13a434d

Browse files
authored
Completed Concept Entry for Javascript: Optional Chaining #5805 (#5826)
* created initial file * added basic description and tags * initial draft is complete * initial draft complete * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update content/javascript/concepts/optional-chaining/optional-chaining.md * Update optional-chaining.md * Fix lint errors * Update optional-chaining.md minor fixes * Update optional-chaining.md format fixed ---------
1 parent b64ea94 commit 13a434d

File tree

1 file changed

+196
-0
lines changed

1 file changed

+196
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
---
2+
Title: 'Optional Chaining'
3+
Description: 'The optional chaining operator allows safe access to nested object properties or methods without having to explicitly check if intermediate properties exist.'
4+
Subjects:
5+
- 'Web Development'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Data'
9+
- 'Operators'
10+
CatalogContent:
11+
- 'introduction-to-javascript'
12+
- 'paths/front-end-engineer-career-path'
13+
---
14+
15+
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.
16+
17+
Optional chaning can be used to validate nested object properties, call optional functions or methods on optional objects, accessing array elements, and more.
18+
19+
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.
20+
21+
## Syntax
22+
23+
The basic syntax for using optional chaining is as follows:
24+
25+
```pseudo
26+
// To access an object property
27+
object?.property;
28+
29+
//To access an element in an array
30+
array?.[index];
31+
32+
//To invoke a function (if it exists)
33+
object?.method?.();
34+
```
35+
36+
## Examples
37+
38+
### Accessing Object Properties
39+
40+
To search for the `state` object of `person`:
41+
42+
```js
43+
const person = {
44+
name: 'Alice',
45+
gender: 'Female',
46+
age: 12,
47+
address: {
48+
street: '1111 Palm Ave',
49+
city: 'Broken Arrow',
50+
state1: 'Oklahoma',
51+
},
52+
favoriteFoods: ['pizza', 'ice cream', 'cake'],
53+
commonPhrase: function () {
54+
return `${this.name} always says "I love ${this.address.state1}."`;
55+
},
56+
};
57+
58+
// Regular syntax for checking if the state1 property exists
59+
const state1Regular = person && person.address && person.address.state1;
60+
console.log(`State (regular syntax) is: ${state1Regular}`);
61+
62+
// This can be rewritten as:
63+
const state1Chaining = person?.address?.state1;
64+
console.log(`State (optional chaining) is: ${state1Chaining}`);
65+
```
66+
67+
The output of the above code will be as follows:
68+
69+
```shell
70+
State (regular syntax) is: Oklahoma
71+
State (optional chaining) is: Oklahoma
72+
```
73+
74+
### Accessing Array Elements
75+
76+
To search for the `cake` in the `favoriteFoods` array of `person`:
77+
78+
```js
79+
const person = {
80+
name: 'Alice',
81+
gender: 'Female',
82+
age: 12,
83+
address: {
84+
street: '1111 Palm Ave',
85+
city: 'Broken Arrow',
86+
state1: 'Oklahoma',
87+
},
88+
favoriteFoods: ['pizza', 'ice cream', 'cake'],
89+
commonPhrase: function () {
90+
return `${this.name} always says "I love ${this.address.state1}."`;
91+
},
92+
};
93+
94+
// Regular Syntax for searching favorite food
95+
const foodRegular =
96+
person &&
97+
person.favoriteFoods &&
98+
person.favoriteFoods.find((item) => item === 'cake');
99+
console.log(`Favorite Food (regular syntax) is: ${foodRegular}`);
100+
101+
// This can be rewritten as:
102+
const foodChaining = person?.favoriteFoods.find((item) => item === 'cake');
103+
console.log(`Favorite Food (optional chaining) is: ${foodChaining}`);
104+
```
105+
106+
The output of the above code will be as follows:
107+
108+
```shell
109+
Favorite Food (regular syntax) is: cake
110+
Favorite Food (optional chaining) is: cake
111+
```
112+
113+
### Accessing Object Functions
114+
115+
To determine if the `commonPhrase` function exists in `person` before invoking it:
116+
117+
```js
118+
//Regular Syntax
119+
if (person && typeof person.commonPhrase === 'function') {
120+
const phrase = person.commonPhrase();
121+
console.log(`${phrase}`);
122+
}
123+
124+
//This can be rewritten as:
125+
const phrase = person?.commonPhrase?.();
126+
console.log(`${phrase}`);
127+
```
128+
129+
The output of the above code will be as follows:
130+
131+
```shell
132+
Alice always says "I love Oklahoma."
133+
Alice always says "I love Oklahoma."
134+
```
135+
136+
## Codebyte Example
137+
138+
Run the following example and compare the regular syntax of conditional statements and optional chaining on a more complex data set:
139+
140+
```codebyte/javascript
141+
const people = [
142+
{
143+
name: "Blake",
144+
gender: "Male",
145+
age: null,
146+
address: {
147+
street: "456 Maple Dr",
148+
city: "Austin",
149+
state: "Texas"
150+
}
151+
},
152+
{
153+
name: "Eve",
154+
gender: "Female",
155+
age: 15,
156+
address: {
157+
street: "789 Birch Ln",
158+
city: "",
159+
state: "Colorado"
160+
}
161+
},
162+
null,
163+
{
164+
name: "David",
165+
gender: "Male",
166+
age: 72,
167+
address: {
168+
street: "123 Acorn St",
169+
city: "Tampa",
170+
state: "Florida"
171+
}
172+
},
173+
{
174+
name: "Jospeh",
175+
gender: "Male",
176+
age: 9,
177+
address: {
178+
street: "987 Pine Ave",
179+
city: "Taos",
180+
state: "New Mexico"
181+
}
182+
}
183+
];
184+
185+
console.log("Using Regular Syntax for City:");
186+
people.forEach((person, index) => {
187+
const city = person && person.address && person.address.city;
188+
console.log(`Person ${index + 1}: City: ${city ?? "Not Available"}`);
189+
});
190+
191+
console.log("\nUsing Optional Chaining for Age:");
192+
people.forEach((person, index) => {
193+
const age = person?.age;
194+
console.log(`Person ${index + 1}: Age: ${age ?? "Not Available"}`);
195+
});
196+
```

0 commit comments

Comments
 (0)