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 || {};
cache = cache ?? new Map();
enabled = enabled && isReady();
title || (title = "Untitled");
user.name = user.name || "guest";
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,
}]
OptionWhat it does
"always" (default)Report code that could use a logical assignment operator.
"never"Report every logical assignment operator.
OptionDefaultWhat it does
enforceForIfStatementsfalseWith "always", also report an if that only assigns to the value it tests.
example.jswith "never"1 problem
options ||= {};
example.jswith "never"No problems
options = options || {};

enforceForIfStatements#

example.jsNo problems
if (!title) {
  title = "Untitled";
}

if (cache == null) cache = new Map();
example.jswith "always", { "enforceForIfStatements": true }2 problems
if (!title) {
  title = "Untitled";
}

if (cache == null) cache = new Map();