Skip to content

Commit 8220a84

Browse files
doc: add new example for logical assignment operator
fix #846
1 parent 7d1b00d commit 8220a84

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

website/catalog/typescript/index.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ However, you can use the [`languageGlobs`](/reference/sgconfig.html#languageglob
1818
<!--@include: ./switch-from-should-to-expect.md-->
1919
<!--@include: ./speed-up-barrel-import.md-->
2020
<!--@include: ./missing-component-decorator.md-->
21-
<!--@include: ./find-import-identifiers.md-->
21+
<!--@include: ./find-import-identifiers.md-->
22+
<!--@include: ./use-logical-assignment.md-->
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
## Use Logical Assignment Operators
2+
3+
* [Playground Link](/playground.html#eyJtb2RlIjoiUGF0Y2giLCJsYW5nIjoiamF2YXNjcmlwdCIsInF1ZXJ5IjoiJEEgPSAkQSB8fCAkQiIsInJld3JpdGUiOiIkQSB8fD0gJEIiLCJzdHJpY3RuZXNzIjoic21hcnQiLCJzZWxlY3RvciI6IiIsImNvbmZpZyI6IiMgWUFNTCBSdWxlIGlzIG1vcmUgcG93ZXJmdWwhXG4jIGh0dHBzOi8vYXN0LWdyZXAuZ2l0aHViLmlvL2d1aWRlL3J1bGUtY29uZmlnLmh0bWwjcnVsZVxucnVsZTpcbiAgYW55OlxuICAgIC0gcGF0dGVybjogY29uc29sZS5sb2coJEEpXG4gICAgLSBwYXR0ZXJuOiBjb25zb2xlLmRlYnVnKCRBKVxuZml4OlxuICBsb2dnZXIubG9nKCRBKSIsInNvdXJjZSI6ImNvbnN0IGEgPSB7IGR1cmF0aW9uOiA1MCwgdGl0bGU6ICcnIH07XG5cbmEuZHVyYXRpb24gPSBhLmR1cmF0aW9uIHx8IDEwO1xuY29uc29sZS5sb2coYS5kdXJhdGlvbik7XG5hLnRpdGxlID0gYS50aXRsZSB8fCAndGl0bGUgaXMgZW1wdHkuJztcbmNvbnNvbGUubG9nKGEudGl0bGUpO1xuIn0=)
4+
5+
### Description
6+
7+
A logical assignment operator in JavaScript combines a logical operation (like OR or nullish coalescing) with an assignment. It updates a variable or property only under specific conditions, making code more concise.
8+
9+
This is a relatively new feature in JavaScript (introduced in ES2021), so older codebases might not use it yet. This rule identifies instances where a variable is assigned a value using a logical OR (`||`) operation and suggests replacing it with the more concise logical assignment operator (`||=`).
10+
11+
### Pattern
12+
13+
```shell
14+
ast-grep -p '$A = $A || $B' -r '$A ||= $B' -l ts
15+
```
16+
17+
### Example
18+
19+
```ts {3,5}
20+
const a = { duration: 50, title: '' };
21+
22+
a.duration = a.duration || 10;
23+
console.log(a.duration);
24+
a.title = a.title || 'title is empty.';
25+
console.log(a.title);
26+
```
27+
28+
### Diff
29+
30+
```ts
31+
const a = { duration: 50, title: '' };
32+
33+
a.duration = a.duration || 10; // [!code --]
34+
a.duration ||= 10; // [!code ++]
35+
console.log(a.duration);
36+
a.title = a.title || 'title is empty.'; // [!code --]
37+
a.title ||= 'title is empty.'; // [!code ++]
38+
console.log(a.title);
39+
```
40+
41+
### Contributed by
42+
Inspired by [this tweet](https://x.com/YTCodeAntonio/status/1973720331656605809).

0 commit comments

Comments
 (0)