Skip to content

Commit 1f0fcb7

Browse files
committed
minor fixes
1 parent 9e59ec1 commit 1f0fcb7

File tree

1 file changed

+7
-8
lines changed
  • 1-js/04-object-basics/07-optional-chaining

1 file changed

+7
-8
lines changed

1-js/04-object-basics/07-optional-chaining/article.md

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,7 @@ AND'ing the whole path to the property ensures that all components exist, but is
4040

4141
The optional chaining `?.` stops the evaluation and returns `undefined` if the part before `?.` is `undefined` or `null`.
4242

43-
Further in this article, for brevity, we'll be saying that something "exists" if it's not `null` and not `undefined`.
44-
43+
**Further in this article, for brevity, we'll be saying that something "exists" if it's not `null` and not `undefined`.**
4544

4645
Here's the safe way to access `user.address.street`:
4746

@@ -57,14 +56,14 @@ Reading the address with `user?.address` works even if `user` object doesn't exi
5756
let user = null;
5857

5958
alert( user?.address ); // undefined
60-
6159
alert( user?.address.street ); // undefined
62-
alert( user?.address.street.anything ); // undefined
6360
```
6461
65-
Please note: the `?.` syntax works exactly where it's placed, not any further.
62+
Please note: the `?.` syntax makes optional the value before it, but not any further.
63+
64+
In the example above, `user?.` allows only `user` to be `null/undefined`.
6665
67-
In the last two lines the evaluation stops immediately after `user?.`, never accessing further properties. But if the `user` actually exists, then the further intermediate properties, such as `user.address` must exist.
66+
On the other hand, if `user` does exist, then it must have `user.address` property, otherwise `user?.address.street` gives an error at the second dot.
6867
6968
```warn header="Don't overuse the optional chaining"
7069
We should use `?.` only where it's ok that something doesn't exist.
@@ -75,13 +74,13 @@ So, if `user` happens to be undefined due to a mistake, we'll know about it and
7574
```
7675
7776
````warn header="The variable before `?.` must be declared"
78-
If there's no variable `user`, then `user?.anything` triggers an error:
77+
If there's no variable `user` at all, then `user?.anything` triggers an error:
7978

8079
```js run
8180
// ReferenceError: user is not defined
8281
user?.address;
8382
```
84-
The optional chaining only tests for `null/undefined`, doesn't interfere with any other language mechanics.
83+
There must be `let/const/var user`. The optional chaining works only for declared variables.
8584
````
8685

8786
## Short-circuiting

0 commit comments

Comments
 (0)