Use Logical Assignment Operators
Description
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.
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 (||=).
Pattern
shell
ast-grep -p '$A = $A || $B' -r '$A ||= $B' -l tsExample
ts
const a = { duration: 50, title: '' };
a.duration = a.duration || 10;
console.log(a.duration);
a.title = a.title || 'title is empty.';
console.log(a.title);Diff
ts
const a = { duration: 50, title: '' };
a.duration = a.duration || 10;
a.duration ||= 10;
console.log(a.duration);
a.title = a.title || 'title is empty.';
a.title ||= 'title is empty.';
console.log(a.title);Contributed by
Inspired by this tweet.