💼 This rule is enabled in the ✅ recommended
config.
🔧 This rule is automatically fixable by the --fix
CLI option.
This rule enforces the use of ternary expressions over 'simple' if-else
statements, where 'simple' means the consequent and alternate are each one line and have the same basic type and form.
Using an if-else
statement typically results in more lines of code than a single-line ternary expression, which leads to an unnecessarily larger codebase that is more difficult to maintain.
Additionally, using an if-else
statement can result in defining variables using let
or var
solely to be reassigned within the blocks. This leads to variables being unnecessarily mutable and prevents prefer-const
from flagging the variable.
function unicorn() {
if (test) {
return a;
} else {
return b;
}
}
function* unicorn() {
if (test) {
yield a;
} else {
yield b;
}
}
async function unicorn() {
if (test) {
await a();
} else {
await b();
}
}
if (test) {
throw new Error('foo');
} else {
throw new Error('bar');
}
let foo;
if (test) {
foo = 1;
} else {
foo = 2;
}
function unicorn() {
return test ? a : b;
}
function* unicorn() {
yield (test ? a : b);
}
async function unicorn() {
await (test ? a() : b());
}
const error = test ? new Error('foo') : new Error('bar');
throw error;
let foo;
foo = test ? 1 : 2;
// Multiple expressions
let foo;
let bar;
if (test) {
foo = 1;
bar = 2;
} else{
foo = 2;
}
// Different expressions
function unicorn() {
if (test) {
return a;
} else {
throw new Error('error');
}
}
// Assign to different variable
let foo;
let bar;
if (test) {
foo = 1;
} else{
baz = 2;
}
Type: string
Default: 'always'
'always'
(default)- Always report when using an
IfStatement
where a ternary expression can be used.
- Always report when using an
'only-single-line'
- Only check if the content of the
if
and/orelse
block is less than one line long.
- Only check if the content of the
The following case is considered valid:
// eslint unicorn/prefer-ternary: ["error", "only-single-line"]
if (test) {
foo = [
'multiple line array'
];
} else {
bar = baz;
}