logical-assignment-operators
Require or disallow the logical assignment operators ||=, &&= and ??=
fixable
options = options || {} names the variable twice, and it assigns even when options keeps its value. options ||= {} says the same thing with one name and only assigns when it needs to.
--fix rewrites the code when the target is a plain variable. A property can have a getter or a setter, and the rewrite can change how often they run, so user.name = user.name || "guest" gets a suggestion instead of a fix.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"logical-assignment-operators" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"logical-assignment-operators" = [
"error",
"always", # "always" or "never"
{
enforceForIfStatements = false,
},
]Examples#
example.js5 problems
options = options || {}Assignment (=) can be replaced with operator assignment (||=).;
cache = cache ?? new Map()Assignment (=) can be replaced with operator assignment (??=).;
enabled = enabled && isReady()Assignment (=) can be replaced with operator assignment (&&=).;
title || (title = "Untitled")Logical expression can be replaced with an assignment (||=).;
user.name = user.name || "guest"Assignment (=) can be replaced with operator assignment (||=).;example.jsNo problems
options ||= {};
cache ??= new Map();
enabled &&= isReady();
title ||= "Untitled";
user.name ||= "guest";Options#
bunfig.toml
[lint.rules]
logical-assignment-operators = ["error", "always", {
enforceForIfStatements = true,
}]| Option | What it does |
|---|---|
"always" (default) | Report code that could use a logical assignment operator. |
"never" | Report every logical assignment operator. |
| Option | Default | What it does |
|---|---|---|
enforceForIfStatements | false | With "always", also report an if that only assigns to the value it tests. |
example.jswith
"never"1 problemoptions ||= {}Unexpected logical operator assignment (||=) shorthand.;example.jswith
"never"No problemsoptions = options || {};enforceForIfStatements#
example.jsNo problems
if (!title) {
title = "Untitled";
}
if (cache == null) cache = new Map();example.jswith
"always", { "enforceForIfStatements": true }2 problemsif (!title) {if statement can be replaced with a logical operator assignment with operator ||=.
title = "Untitled";
}
if (cache == null) cache = new Map();if statement can be replaced with a logical operator assignment with operator ??=.