Skip to content
← Back to rules

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);

Configuration ​

This rule accepts a configuration object with the following properties:

defaultAssignment ​

type: boolean

default: true

Whether to allow the default assignment pattern x ? x : y.

When set to false, the rule also flags cases like x ? x : y and suggests using the logical OR form x || y instead. When true (default), such default assignments are allowed and not reported.

How to use ​

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

json
{
  "rules": {
    "no-unneeded-ternary": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "no-unneeded-ternary": "error",
  },
});
bash
oxlint --deny no-unneeded-ternary

Version ​

This rule was added in v0.15.12.

References ​