Skip to content

Commit fd77bbe

Browse files
khadijagardeziljharb
authored andcommittedJul 2, 2023
[guide] add nullish-coalescing-operator definition
1 parent 7916d6f commit fd77bbe

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
 

‎README.md

+27
Original file line numberDiff line numberDiff line change
@@ -2198,6 +2198,33 @@ Other Style Guides
21982198
const bar = a + (b / c) * d;
21992199
```
22002200

2201+
<a name="nullish-coalescing-operator"></a>
2202+
- [15.9](#nullish-coalescing-operator) The nullish coalescing operator (`??`) is a logical operator that returns its right-hand side operand when its left-hand side operand is `null` or `undefined`. Otherwise, it returns the left-hand side operand.
2203+
2204+
> Why? It provides precision by distinguishing null/undefined from other falsy values, enhancing code clarity and predictability.
2205+
2206+
```javascript
2207+
// bad
2208+
const value = 0 ?? 'default';
2209+
// returns 0, not 'default'
2210+
2211+
// bad
2212+
const value = '' ?? 'default';
2213+
// returns '', not 'default'
2214+
2215+
// good
2216+
const value = null ?? 'default';
2217+
// returns 'default'
2218+
2219+
// good
2220+
const user = {
2221+
name: 'John',
2222+
age: null
2223+
};
2224+
const age = user.age ?? 18;
2225+
// returns 18
2226+
```
2227+
22012228
**[⬆ back to top](#table-of-contents)**
22022229

22032230
## Blocks

0 commit comments

Comments
 (0)
Failed to load comments.