Skip to content

eslint/no-unneeded-ternary Suspicious

⚠️🛠️️ A dangerous auto-fix is available for this rule.

What it does

Disallow ternary operators when simpler alternatives exist

Why is this bad?

It’s a common mistake in JavaScript to use a conditional expression to select between two Boolean values instead of using ! to convert the test to a Boolean.

Another common mistake is using a single variable as both the conditional test and the consequent. In such cases, the logical OR can be used to provide the same functionality.

Examples

Examples of incorrect code for this rule:

js
const isYes = answer === 1 ? true : false;
const isNo = answer === 1 ? false : true;

foo(bar ? bar : 1);

Examples of correct code for this rule:

js
const isYes = answer === 1;
const isNo = answer !== 1;

foo(bar || 1);

How to use

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny no-unneeded-ternary
json
{
  "rules": {
    "no-unneeded-ternary": "error"
  }
}

References

Released under the MIT License.