1 # disallow ternary operators when simpler alternatives exist (no-unneeded-ternary)
3 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.
4 Here are some examples:
8 var isYes = answer === 1 ? true : false;
11 var isYes = answer === 1;
15 var isNo = answer === 1 ? false : true;
18 var isNo = answer !== 1;
21 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.
34 This rule disallow ternary operators when simpler alternatives exist.
36 Examples of **incorrect** code for this rule:
39 /*eslint no-unneeded-ternary: "error"*/
41 var a = x === 2 ? true : false;
43 var a = x ? true : false;
46 Examples of **correct** code for this rule:
49 /*eslint no-unneeded-ternary: "error"*/
51 var a = x === 2 ? "Yes" : "No";
55 var a = x ? "Yes" : "No";
59 f(x ? x : 1); // default assignment - would be disallowed if defaultAssignment option set to false. See option details below.
64 This rule has an object option:
66 * `"defaultAssignment": true` (default) allows the conditional expression as a default assignment pattern
67 * `"defaultAssignment": false` disallows the conditional expression as a default assignment pattern
71 When set to `true`, which it is by default, The defaultAssignment option allows expressions of the form `x ? x : expr` (where `x` is any identifier and `expr` is any expression).
73 Examples of additional **incorrect** code for this rule with the `{ "defaultAssignment": false }` option:
76 /*eslint no-unneeded-ternary: ["error", { "defaultAssignment": false }]*/
83 Note that `defaultAssignment: false` still allows expressions of the form `x ? expr : x` (where the identifier is on the right hand side of the ternary).
87 You can turn this rule off if you are not concerned with unnecessary complexity in conditional expressions.
91 * [no-ternary](no-ternary.md)
92 * [no-nested-ternary](no-nested-ternary.md)