unicorn/no-lonely-if
Disallow an if as the only statement in another if when neither has an else
Two nested if statements with nothing else between them test one combined condition. Join them with && and you lose a level of indentation and get the whole condition in one place.
no-lonely-if without the unicorn/ prefix is a different rule. It reports an if that's the only thing in an else block.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/no-lonely-if" = "error" # or "warn"Examples#
example.js1 problem
if (user) {
ifUnexpected if as the only statement in a if block without else. (user.isAdmin) {
showSettings();
}
}example.jsNo problems
if (user && user.isAdmin) {
showSettings();
}You can't merge the two when either one has an else, or when the outer block does something else as well:
example.jsNo problems
if (user) {
if (user.isAdmin) {
showSettings();
}
} else {
showLogin();
}
if (user) {
greet(user);
if (user.isAdmin) {
showSettings();
}
}