unicorn/prefer-logical-operator-over-ternary

Require || or ?? instead of a ternary that repeats its condition

has suggestions

user.name ? user.name : "Anonymous" writes user.name twice and evaluates it twice. user.name || "Anonymous" gives the same result and evaluates it once.

The rule reports a ? a : b and !a ? b : a.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/prefer-logical-operator-over-ternary" = "error" # or "warn"

Examples#

example.js2 problems
const name = user.name ? user.name : "Anonymous";
const port = !config.port ? 3000 : config.port;
example.jsNo problems
const name = user.name || "Anonymous";
const port = config.port || 3000;

If the fallback is only meant for null and undefined, so that 0 and "" are kept, use ??:

example.jsNo problems
const port = config.port ?? 3000;