You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/07-optional-chaining/article.md
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -25,14 +25,14 @@ That's the expected result. JavaScript works like this. As `user.address` is `un
25
25
26
26
That said, in many practical cases we'd prefer to get `undefined` instead of an error here (meaning "no street").
27
27
28
-
...And another example. In the web development, we may need the information about an element on the page. The element is returned by `document.querySelector('.elem')`, and the catch is again - that it sometimes doesn't exist:
28
+
...And another example. In the web development, we may need the information about an element on the page. We can find this element using a special method call, such as `document.querySelector('.elem')`, and it either returns an object or `null` when there's no such element.
29
29
30
30
```js run
31
-
// the result of the call document.querySelector('.elem') may be an object or null
31
+
// the result of the call document.querySelector('.elem') may be null
32
32
let html =document.querySelector('.elem').innerHTML; // error if it's null
33
33
```
34
34
35
-
Once again, we may want to avoid the error in such case.
35
+
Once again, if the element doesn't exist, we'll get an error accessing `.innerHTML` of `null`. And in some cases, when the absence of the element is normal, we'd like to avoid the error and just accept `html = null` as the result.
...But that's quite inelegant. As you can see, the `user.address` is duplicated in the code. For more deeply nested properties, that becomes a problem.
47
+
It works, there's no error...But it's quite inelegant. As you can see, the `"user.address"` appears twice in the code. For more deeply nested properties, that becomes a problem as more repetitions are required.
48
48
49
49
E.g. let's try getting `user.address.street.name`.
50
50
@@ -56,9 +56,9 @@ let user = {}; // user has no address
0 commit comments