Skip to content

Commit 9adc948

Browse files
committed
Optional chaining
1 parent 50e0acd commit 9adc948

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

js/red-javascript-style-guide/readme.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,26 @@ In the following situations:
240240

241241
Use `undefined`, avoid `null`. `undefined` is the default that is already used by the language, for example: destructuring when missing, default return value, unassigned variable etc.
242242

243+
#### Optional chaining
244+
245+
Yes.
246+
247+
The chain stops when expecting a value from undefined.
248+
Know the difference between those:
249+
250+
```js
251+
(undefined)?.startsWith(`a`); // undefined
252+
{}?.startsWith(`b${1+2}`); // TypeError and what is inside the parentheses is computed
253+
{}?.startsWith?.(`c`); // undefined
254+
255+
{}.a?.b?.c?.["d"] // undefined
256+
```
257+
In the second example we expect a value from undefined and the chain immediately stops.
258+
259+
In the second example we expect a value from an object (startsWith), which resolves to undefined, and then we call it (cannot call undefined).
260+
261+
In the third example we also use an optional call (?. + parentheses) to only call it if it is callable.
262+
243263
### Booleans
244264
245265
`true` or `false`, use `Boolean` function to force cast to a Boolean. Do not use `!!` to cast to a Boolean. Leverage truthy values in `if` and `while`.

0 commit comments

Comments
 (0)